dsh-fish-soul 0.18.16 → 0.18.17

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.18.16**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.18.17**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -15,13 +15,15 @@ window.__ModuleLoader__.load({
15
15
  const VIDEO_PROVIDERS = [
16
16
  { value: "volc", label: "火山方舟" },
17
17
  { value: "minimax", label: "MiniMax" },
18
- { value: "openai-compat", label: "OpenAI 兼容" }
18
+ { value: "openai-compat", label: "OpenAI 兼容" },
19
+ { value: "openmotion", label: "OpenMotion(本地渲染)" }
19
20
  ];
20
21
  // 各家常用接口地址示例(接口地址、API Key、模型名都必须填;填错会被对方拒绝)。
21
22
  const VIDEO_BASE_URLS = {
22
23
  volc: "https://ark.cn-beijing.volces.com/api/v3",
23
24
  minimax: "https://api.minimax.cn",
24
- "openai-compat": "https://api.openai.com/v1"
25
+ "openai-compat": "https://api.openai.com/v1",
26
+ openmotion: "http://127.0.0.1:4173"
25
27
  };
26
28
  const VIDEO_RATIOS = [{ value: "9:16", label: "9:16 竖屏" }, { value: "16:9", label: "16:9 横屏" }, { value: "1:1", label: "1:1 方形" }];
27
29
  const VIDEO_RESOLUTIONS = [{ value: "480P", label: "480P" }, { value: "768P", label: "768P" }, { value: "2K", label: "2K" }];
package/lib/gateway.js CHANGED
@@ -112,8 +112,15 @@ export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget'];
112
112
  export const RELAY_TOOL = 'send_elsewhere';
113
113
  /** 熟人传话:白名单里的人托她给白名单里的另一个人带句话(默认关)。 */
114
114
  export const RELAY_FRIEND_TOOL = 'relay_to_friend';
115
- /** 聊天会话里放行的插件工具(记忆 + 跨平台转达)。 */
116
- export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL];
115
+ /** 抖音发视频:主人在私聊里让她做一条视频并发抖音。 */
116
+ export const DOUYIN_VIDEO_TOOL = 'make_douyin_video';
117
+ /** 聊天会话里放行的插件工具(记忆 + 跨平台转达 + 熟人传话 + 抖音发视频)。 */
118
+ export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL];
119
+ /** OpenMotion MCP 工具名识别(兼容 mcp__openmotion__* 与 openmotion_*)。 */
120
+ export function isOpenMotionTool(name) {
121
+ const s = String(name ?? '');
122
+ return /^(?:mcp__openmotion__|openmotion_)[A-Za-z0-9_.-]+$/.test(s);
123
+ }
117
124
  /** 宿主的联网工具:设置里打开「让她能上网查」才放行(护栏按天限次数)。 */
118
125
  export const WEB_TOOLS = ['web_search', 'web_fetch'];
119
126
  /** 自己填 key 的搜索服务(插件注册的工具) */
@@ -684,13 +691,26 @@ export class ChatGateway {
684
691
  /**
685
692
  * 会话里放行哪些工具。插件自己的工具按全局表筛;DSH 的联网工具(web_search / web_fetch)是按会话挂的,
686
693
  * 全局表里经常查不到(#26),不筛——真没有时模型调不到而已。agentCtx 有自己的工具表时也认它。
694
+ * 主人私聊会话额外放行已挂载的 OpenMotion MCP 工具(由 tools.guard 再兜底校验主人身份)。
687
695
  * #37:tools.sessionAllow = 'master' / 'all' 时放开宿主全部工具(restrict 都不调,让会话拿到默认组合)。
688
696
  */
689
- allowedTools(agentCtx) {
697
+ allowedTools(agentCtx, channelId) {
690
698
  const has = (reg, n) => { try { return typeof reg?.get === 'function' && reg.get(n) !== undefined; } catch { return false; } };
691
- const tools = this.ctx.tools;
692
- return [...CHAT_TOOLS, ...WEB_TOOLS, OWN_WEB_TOOL, ...(this.voiceGuardReady ? ['sound_read'] : [])].filter((n) =>
699
+ const tools = this.ctx?.tools;
700
+ const listNames = (reg) => {
701
+ try {
702
+ if (typeof reg?.definitions === 'function') return (reg.definitions() ?? []).map((t) => t?.name).filter(Boolean);
703
+ if (typeof reg?.list === 'function') return (reg.list() ?? []).map((t) => (typeof t === 'string' ? t : t?.name)).filter(Boolean);
704
+ } catch { /* 忽略 */ }
705
+ return [];
706
+ };
707
+ const isMaster = channelId !== undefined && typeof this.isMasterChannel === 'function' && this.isMasterChannel(channelId);
708
+ const omTools = isMaster
709
+ ? [...new Set([...listNames(tools), ...listNames(agentCtx?.tools)].filter(isOpenMotionTool))]
710
+ : [];
711
+ const base = [...CHAT_TOOLS, ...WEB_TOOLS, OWN_WEB_TOOL, ...(this.voiceGuardReady ? ['sound_read'] : [])].filter((n) =>
693
712
  WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n));
713
+ return [...new Set([...base, ...omTools])];
694
714
  }
695
715
 
696
716
  /** 传话配置:熟人托她给另一个人带句话(默认关,白名单按平台 uid 精确匹配)。 */
@@ -749,7 +769,7 @@ export class ChatGateway {
749
769
  }
750
770
  }
751
771
  if (channelId !== undefined && this.sessionOpenFor(channelId)) return; // #37 主人/全部放开:不 restrict,会话用宿主默认工具组合
752
- const allow = this.allowedTools(agentCtx);
772
+ const allow = this.allowedTools(agentCtx, channelId);
753
773
  if (typeof agentCtx?.tools?.restrict === 'function' && allow.length > 0) {
754
774
  try {
755
775
  agentCtx.tools.restrict({ allow });
package/lib/index.js CHANGED
@@ -47,7 +47,7 @@ import { DouyinHttp } from './douyin-http.js';
47
47
  import { fishSoulConfigSchema } from './config-schema.js';
48
48
  import { loadSharp, sharpReady } from './imageconv.js';
49
49
  import {
50
- ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf
50
+ ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, WEB_TOOLS, OWN_WEB_TOOL, isOpenMotionTool, splitChannelId, sessionChannelOf
51
51
  } from './gateway.js';
52
52
  import { platformLabelOf, platformOf, parseRelayTarget } from './gateway-util.js';
53
53
  import { douyinVideoIdsOf } from './douyin-adapter.js';
@@ -1268,6 +1268,10 @@ async function startup(ctx, config, { log, gate }) {
1268
1268
  const row = gateway?.chatForSession(id);
1269
1269
  return row !== null && row !== undefined && gateway.sessionOpenFor(row.channel_id) === true;
1270
1270
  };
1271
+ const isMasterSession = (id) => {
1272
+ const row = gateway?.chatForSession(id);
1273
+ return row !== null && row !== undefined && gateway.isMasterChannel(row.channel_id) === true;
1274
+ };
1271
1275
  ctx.effect(() => {
1272
1276
  const off = ctx.tools.guard((exec) => {
1273
1277
  const id = exec?.agent?.id;
@@ -1305,6 +1309,9 @@ async function startup(ctx, config, { log, gate }) {
1305
1309
  }
1306
1310
  if (exec.name === 'run_code') return `聊天会话里不能运行代码(放开工具也不放 run_code:它能跑任意程序)`;
1307
1311
  if (sessionOpen(id)) return undefined; // #37 主人/全部放开:宿主工具都放
1312
+ if (isOpenMotionTool(exec.name)) {
1313
+ return isMasterSession(id) ? undefined : 'OpenMotion 视频工具只能在主人的私聊里用';
1314
+ }
1308
1315
  return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达、熟人传话和上网查;设置页「模型」里可以放开)`;
1309
1316
  });
1310
1317
  gateway.voiceGuardReady = true;
@@ -1580,6 +1587,42 @@ async function startup(ctx, config, { log, gate }) {
1580
1587
  }
1581
1588
  })), 'dsh-fish-soul: relay_to_friend');
1582
1589
 
1590
+ // ── 工具:make_douyin_video(主人在私聊里让她做一条视频并发到抖音)──
1591
+ ctx.effect(() => ctx.tools.register(defineTool({
1592
+ name: DOUYIN_VIDEO_TOOL,
1593
+ description: '按给定或自己想的画面文案生成一条短视频并发到抖音(服务商配成 OpenMotion 时走本地渲染,配成云端服务商时调对应视频模型)。' +
1594
+ '只有主人明确要求(「做个视频发抖音」「用 OpenMotion 做条视频发出去」这类)时才用,别自己找机会用。只能在主人的私聊里用。',
1595
+ parameters: objectSchema({
1596
+ text: { type: 'string', description: '视频画面/配文(15~80 字,写视频里在拍什么或画面里的文案;不填就由你自己按此刻心情写一条)' }
1597
+ }),
1598
+ output: textOutput,
1599
+ async execute(args, toolCtx) {
1600
+ const session = sessionForTool(toolCtx);
1601
+ const channelId = String(session.channelId ?? '');
1602
+ if (channelId === '' || gateway === null) return '不知道现在是在哪个聊天里,先不发。';
1603
+ if (!gateway.isMasterChannel(channelId)) return '这个只能在主人的私聊里用。';
1604
+ if ((currentConfig.douyin ?? {}).enabled !== true) return '抖音总开关没开(设置页「抖音」→ 抖音接入)。';
1605
+ if (!douyinSocial) return '抖音模块没加载。';
1606
+ if (!douyinSocial.cfg().video.enabled) return '还没打开「自己发视频」(设置页「抖音」→ 作品和评论 → 自己发视频)。';
1607
+ const blocked = douyinSocial.postBlockReason?.();
1608
+ if (blocked) return `现在发不了:${blocked}。`;
1609
+ if (douyinSocial.posting) return '正在发另一条作品,稍等会儿再试。';
1610
+ if (!douyinSocial.ready) return `抖音还没准备好:${douyinSocial.notReadyText()}。`;
1611
+ const quotaErr = douyinSocial.videoQuotaError?.();
1612
+ if (quotaErr) return `今天发不了:${quotaErr}。`;
1613
+ const text = String(args?.text ?? '').trim();
1614
+ try {
1615
+ const r = await douyinSocial.post({ force: true, kind: 'video', ...(text !== '' ? { text } : {}) });
1616
+ if (!r?.ok) return `没发成:${r?.error ?? '原因不明'}。`;
1617
+ return `已经生成并发布到抖音了:${r.text}。`;
1618
+ } catch (error) {
1619
+ const msg = String(error instanceof Error ? error.message : error);
1620
+ log('warn', `[fish-soul] 聊天触发发抖音视频失败:${msg}`);
1621
+ return `没发成:${msg.slice(0, 120)}。`;
1622
+ }
1623
+ }
1624
+ })), 'dsh-fish-soul: make_douyin_video');
1625
+
1583
1626
  // ── 工具:fish_search(自己填 key 的搜索服务;只在鱼的聊天会话里能用,开关 / 次数由上面的护栏管)──
1584
1627
  ctx.effect(() => ctx.tools.register(defineTool({
1585
1628
  name: OWN_WEB_TOOL,
package/lib/social.js CHANGED
@@ -277,8 +277,8 @@ export class SocialBase {
277
277
  ].filter((l) => l !== '').join('\n');
278
278
  }
279
279
 
280
- /** 写一条并发出去。force = 设置页"现在发一条"(不看次数和间隔,但还是可以 [不发])。 */
281
- async post({ parts, slot, mood, force = false, kind = 'post' } = {}) {
280
+ /** 写一条并发出去。force = 设置页"现在发一条"(不看次数和间隔,但还是可以 [不发]);text = 直接按给定文案发,不再让模型写一遍。 */
281
+ async post({ parts, slot, mood, force = false, kind = 'post', text: directText } = {}) {
282
282
  const blocked = this.postBlockReason?.();
283
283
  if (blocked) return { ok: false, error: blocked };
284
284
  if (this.posting) return { ok: false, error: '正在发,稍等' };
@@ -291,7 +291,8 @@ export class SocialBase {
291
291
  if (!force) setKv(this.db, this.postKey(kind), { ...st, tries: st.tries + 1, lastVirtual: this.clock.now() });
292
292
  let jobId = null;
293
293
  try {
294
- const raw = String((await this.callLlm(this.postPrompt({ parts: p, slot, mood, kind }))) ?? '').trim();
294
+ const given = typeof directText === 'string' && directText.trim() !== '' ? directText.trim() : '';
295
+ const raw = given !== '' ? given : String((await this.callLlm(this.postPrompt({ parts: p, slot, mood, kind }))) ?? '').trim();
295
296
  if (raw === '' || /\[不发\]/.test(raw)) {
296
297
  this.note('post', { title: this.label, reason: raw === '' ? '想发条动态,但没写出来' : '想了想,今天先不发动态' });
297
298
  return { ok: false, skipped: true, error: raw === '' ? '模型没写出来' : '她说先不发' };
package/lib/video-gen.js CHANGED
@@ -10,13 +10,15 @@
10
10
  // 逐块下、边下边写盘,不把整条视频收进内存。
11
11
 
12
12
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, renameSync, statSync, statfsSync, unlinkSync, writeSync } from 'node:fs';
13
- import { randomBytes } from 'node:crypto';
13
+ import { randomBytes, randomUUID } from 'node:crypto';
14
14
  import { join, resolve } from 'node:path';
15
15
  import { safeDownloadStream } from './safe-download.js';
16
16
  import { scrubSecrets } from './voice.js';
17
17
 
18
18
  const MB = 1024 * 1024;
19
- const PROVIDERS = new Set(['volc', 'minimax', 'openai-compat']);
19
+ const PROVIDERS = new Set(['volc', 'minimax', 'openai-compat', 'openmotion']);
20
+ const OPENMOTION_DEFAULT_URL = 'http://127.0.0.1:4173';
21
+ const OPENMOTION_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
20
22
  const RATIOS = new Set(['16:9', '9:16', '1:1']);
21
23
  const RESOLUTIONS = new Set(['480P', '768P', '2K']); // MiniMax 官方 resolution 枚举
22
24
  const FREE_MIN = 1024 * MB; // 剩不到 1GB 就不生成:写一半失败比不生成更糟
@@ -187,10 +189,86 @@ export function durationFor(provider, cfg) {
187
189
  // 取整:官方 schema 里 duration 是 integer(5.5 会被严格校验拒掉)
188
190
  const sec = Number.isFinite(raw) ? Math.round(raw) : 5;
189
191
  if (provider === 'openai-compat') return openaiSeconds(raw);
192
+ if (provider === 'openmotion') return Math.min(15, Math.max(4, sec));
190
193
  if (provider === 'minimax') return Math.min(15, Math.max(minimaxMinDuration(cfg?.model), sec));
191
194
  return Math.min(12, Math.max(4, sec)); // volc
192
195
  }
193
196
 
197
+ const escapeHtml = (s) => String(s ?? '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
198
+
199
+ /**
200
+ * 校验 OpenMotion 本地服务地址:只允许本机回环 http://127.0.0.1|localhost|[::1]:port。
201
+ */
202
+ export function openmotionOrigin(baseURL) {
203
+ const raw = String(baseURL ?? '').trim() || OPENMOTION_DEFAULT_URL;
204
+ let u;
205
+ try { u = new URL(raw); } catch { return ''; }
206
+ if (u.protocol !== 'http:' || !OPENMOTION_HOSTS.has(u.hostname.toLowerCase()) || !u.port || u.username || u.password) return '';
207
+ if (u.pathname !== '/' && u.pathname !== '') return '';
208
+ return u.origin;
209
+ }
210
+
211
+ /**
212
+ * 把一段文案拆成 1~4 幕卡片,生成带 GSAP 暂停时间线的原生 Hyperframes index.html。
213
+ */
214
+ export function buildOpenMotionHtml(prompt, cfg) {
215
+ const ratio = cfg?.aspectRatio ?? '9:16';
216
+ const [width, height] = ratio === '16:9' ? [1920, 1080] : ratio === '1:1' ? [1080, 1080] : [1080, 1920];
217
+ const duration = durationFor('openmotion', cfg);
218
+ const rawLines = String(prompt ?? '')
219
+ .split(/[\n。!?!?;;]+/)
220
+ .map((s) => s.trim())
221
+ .filter(Boolean);
222
+ const scenes = (rawLines.length ? rawLines : [String(prompt ?? '').trim() || '此刻']).slice(0, 4);
223
+ const seg = Number((duration / scenes.length).toFixed(2));
224
+ const cards = scenes.map((line, i) => {
225
+ const isFirst = i === 0;
226
+ return `<div id="card-${i}" class="card${isFirst ? ' lead' : ''}">` +
227
+ `<div class="tag">${String(i + 1).padStart(2, '0')} / ${String(scenes.length).padStart(2, '0')}</div>` +
228
+ `<div class="line">${escapeHtml(line.slice(0, 60))}</div>` +
229
+ `</div>`;
230
+ }).join('\n ');
231
+ const anims = scenes.map((_, i) => {
232
+ const tIn = Number((i * seg).toFixed(2));
233
+ const tOut = Number(((i + 1) * seg - 0.35).toFixed(2));
234
+ const fadeIn = `tl.fromTo('#card-${i}', { opacity: 0, y: 48, scale: 0.96 }, { opacity: 1, y: 0, scale: 1, duration: 0.45, ease: 'power3.out' }, ${tIn});`;
235
+ const fadeOut = i < scenes.length - 1 && tOut > tIn + 0.45
236
+ ? `\n tl.to('#card-${i}', { opacity: 0, y: -32, duration: 0.3, ease: 'power2.in' }, ${tOut});`
237
+ : '';
238
+ return fadeIn + fadeOut;
239
+ }).join('\n ');
240
+ const fontSize = width >= 1920 ? 64 : 56;
241
+ return `<!doctype html>
242
+ <html lang="zh-CN">
243
+ <head>
244
+ <meta charset="utf-8">
245
+ <title>${escapeHtml(scenes[0].slice(0, 24))}</title>
246
+ <script src="assets/gsap.min.js"></script>
247
+ <style>
248
+ * { box-sizing: border-box; margin: 0; padding: 0; }
249
+ html, body { width: ${width}px; height: ${height}px; overflow: hidden; background: #0b0d13; font-family: "PingFang SC", "Microsoft YaHei", sans-serif; }
250
+ #main { position: relative; width: ${width}px; height: ${height}px; overflow: hidden; background: radial-gradient(circle at 20% 20%, #1c2541 0%, #0b0d13 70%); color: #f5f7ff; }
251
+ #glow { position: absolute; width: ${Math.round(width * 0.7)}px; height: ${Math.round(width * 0.7)}px; left: 15%; top: 20%; border-radius: 50%; background: radial-gradient(circle, rgba(77,107,254,0.26) 0%, rgba(77,107,254,0) 70%); }
252
+ .card { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: ${Math.round(width * 0.1)}px; text-align: center; opacity: 0; }
253
+ .tag { font-size: 24px; letter-spacing: 0.18em; color: rgba(245,247,255,0.55); margin-bottom: 28px; }
254
+ .line { font-size: ${fontSize}px; font-weight: 700; line-height: 1.42; max-width: ${Math.round(width * 0.82)}px; text-shadow: 0 8px 28px rgba(0,0,0,0.45); word-break: break-word; }
255
+ </style>
256
+ </head>
257
+ <body>
258
+ <div id="main" data-composition-id="main" data-start="0" data-duration="${duration}" data-width="${width}" data-height="${height}" data-fps="30">
259
+ <div id="glow"></div>
260
+ ${cards}
261
+ </div>
262
+ <script>
263
+ const tl = gsap.timeline({ paused: true });
264
+ tl.fromTo('#glow', { scale: 0.9, opacity: 0.6 }, { scale: 1.12, opacity: 1, duration: ${duration}, ease: 'sine.inOut' }, 0);
265
+ ${anims}
266
+ window.__timelines = { main: tl };
267
+ </script>
268
+ </body>
269
+ </html>`;
270
+ }
271
+
194
272
  /** 提交生成的请求体(各家形状不一样)。 */
195
273
  export function buildSubmit(provider, cfg, prompt) {
196
274
  const text = String(prompt ?? '');
@@ -317,6 +395,19 @@ export function readPoll(provider, json, { apiKey = '' } = {}) {
317
395
  if (status === 'queued') return { state: 'queued' };
318
396
  return { state: 'running' };
319
397
  }
398
+ if (provider === 'openmotion') {
399
+ const job = j.exportJob && typeof j.exportJob === 'object' ? j.exportJob : (j.job && typeof j.job === 'object' ? j.job : j);
400
+ const st = String(job.state ?? job.status ?? '').trim().toLowerCase();
401
+ if (st === 'completed' || st === 'succeeded') {
402
+ const id = pickUrl(job.id);
403
+ const url = pickUrl(job.downloadUrl) ?? (id ? `/api/exports/${encodeURIComponent(id)}/file` : undefined);
404
+ return { state: 'succeeded', url };
405
+ }
406
+ if (st === 'failed') return { state: 'failed', error: failText(job, j.error, apiKey) };
407
+ if (st === 'cancelled' || st === 'canceled' || st === 'expired') return { state: 'expired' };
408
+ if (st === 'pending' || st === 'queued') return { state: 'queued' };
409
+ return { state: 'running' };
410
+ }
320
411
  if (status === 'succeeded') { const url = pickUrl(j.content?.video_url); return { state: 'succeeded', url }; }
321
412
  if (status === 'failed') return { state: 'failed', error: failText(j, undefined, apiKey) };
322
413
  if (status === 'expired' || status === 'cancelled' || status === 'canceled') return { state: 'expired' };
@@ -456,6 +547,191 @@ function sameOrigin(a, b) {
456
547
  * @param {Function} [opt.downloadImpl] 下载器(默认 safeDownloadStream:逐跳校验、只连公网)
457
548
  * @returns {Promise<{ok:true, file:string, bytes:number, provider:string, elapsedMs:number}|{ok:false, code:string, error:string}>}
458
549
  */
550
+ /**
551
+ * 通过本机 OpenMotion 服务生成并导出 MP4:
552
+ * 1. 创建独立工程(openmotion_create_project)
553
+ * 2. 写入 Hyperframes HTML+GSAP 时间线(openmotion_edit_project)
554
+ * 3. 提交后台渲染(openmotion_export_request)
555
+ * 4. 轮询完成状态(openmotion_get_project)
556
+ * 5. 从 /api/exports/{jobId}/file 流式落盘并校验 ftyp 头
557
+ */
558
+ async function generateOpenMotionVideo(cfg, { prompt, outDir, fetchImpl, nap, clock, signal }) {
559
+ let submitted = false;
560
+ let taskId = '';
561
+ const fail = (code, detail = '') => ({
562
+ ok: false, code, error: videoErrorText(code, detail, ''),
563
+ submitted, ...(taskId ? { taskId } : {})
564
+ });
565
+ const origin = openmotionOrigin(cfg.baseURL);
566
+ if (!origin) return fail('NOT_CONFIGURED', 'OpenMotion 接口地址只允许本机回环(如 http://127.0.0.1:4173)');
567
+ const t0 = clock();
568
+ const headers = { 'Content-Type': 'application/json', Origin: origin };
569
+ const callPhase1 = async (name, args) => {
570
+ const res = await fetchImpl(`${origin}/motion-api/phase1/call`, {
571
+ method: 'POST',
572
+ headers,
573
+ redirect: 'error',
574
+ body: JSON.stringify({ name, arguments: args }),
575
+ signal: timeoutSignal(cfg.timeoutMs, signal)
576
+ });
577
+ let json = null;
578
+ try { json = await res?.json?.(); } catch { json = null; }
579
+ return { res, json };
580
+ };
581
+
582
+ const title = String(prompt ?? '').replace(/[\r\n\x00-\x1f]+/g, ' ').trim().slice(0, 32) || '随手拍';
583
+ let created;
584
+ try {
585
+ created = await callPhase1('openmotion_create_project', {
586
+ requestId: randomUUID(),
587
+ projectType: 'natural_language',
588
+ title,
589
+ requirements: String(prompt ?? '').trim().slice(0, 4000)
590
+ });
591
+ } catch (e) {
592
+ return fail(classifyError(e, 'NETWORK'));
593
+ }
594
+ if (!created.res || !created.res.ok) {
595
+ const msg = created.json ? failText(created.json, undefined, '') : '';
596
+ try { await created.res?.body?.cancel?.(); } catch { /* 忽略取消流失败 */ }
597
+ return fail('SUBMIT_FAILED', msg && msg !== '对方没说失败原因' ? msg : `接口返回 ${created.res?.status ?? '未知'}`);
598
+ }
599
+ const projectId = String(created.json?.projectId ?? '').trim();
600
+ const rev0 = String(created.json?.revision ?? '').trim();
601
+ const ver0 = String(created.json?.currentVersionId ?? created.json?.version?.versionId ?? '').trim();
602
+ if (!projectId || !rev0 || !ver0) return fail('SUBMIT_FAILED', 'OpenMotion 未返回工程版本号');
603
+
604
+ const html = buildOpenMotionHtml(prompt, cfg);
605
+ let edited;
606
+ try {
607
+ edited = await callPhase1('openmotion_edit_project', {
608
+ projectId,
609
+ requestId: randomUUID(),
610
+ expectedRevision: rev0,
611
+ expectedVersionId: ver0,
612
+ presentation: 'background',
613
+ summary: 'Write video composition',
614
+ files: [{ path: 'index.html', content: html }]
615
+ });
616
+ } catch (e) {
617
+ return fail(classifyError(e, 'NETWORK'));
618
+ }
619
+ if (!edited.res || !edited.res.ok) {
620
+ const msg = edited.json ? failText(edited.json, undefined, '') : '';
621
+ try { await edited.res?.body?.cancel?.(); } catch { /* 忽略取消流失败 */ }
622
+ return fail('SUBMIT_FAILED', msg && msg !== '对方没说失败原因' ? msg : `写工程失败(${edited.res?.status ?? '未知'})`);
623
+ }
624
+ const rev1 = String(edited.json?.revision ?? '').trim();
625
+ const ver1 = String(edited.json?.version?.versionId ?? edited.json?.currentVersionId ?? '').trim();
626
+ if (!rev1 || !ver1) return fail('SUBMIT_FAILED', 'OpenMotion 写工程后未返回新版本');
627
+
628
+ submitted = true;
629
+ let exported;
630
+ try {
631
+ exported = await callPhase1('openmotion_export_request', {
632
+ projectId,
633
+ requestId: randomUUID(),
634
+ expectedRevision: rev1,
635
+ versionId: ver1,
636
+ audio: 'optional'
637
+ });
638
+ } catch (e) {
639
+ return fail(classifyError(e, 'NETWORK'));
640
+ }
641
+ if (!exported.res || !exported.res.ok) {
642
+ const msg = exported.json ? failText(exported.json, undefined, '') : '';
643
+ try { await exported.res?.body?.cancel?.(); } catch { /* 忽略取消流失败 */ }
644
+ return fail('SUBMIT_FAILED', msg && msg !== '对方没说失败原因' ? msg : `提交渲染失败(${exported.res?.status ?? '未知'})`);
645
+ }
646
+ const jobId = String(exported.json?.job?.id ?? exported.json?.id ?? '').trim();
647
+ if (!jobId || jobId === '.' || jobId === '..' || /[\\/]/.test(jobId)) return fail('SUBMIT_FAILED', '没拿到渲染任务号');
648
+ taskId = jobId;
649
+
650
+ const maxPolls = Math.max(1, Math.ceil(cfg.pollBudgetMs / cfg.pollIntervalMs) + 2);
651
+ let downloadPath = '';
652
+ let polls = 0;
653
+ for (;;) {
654
+ if (clock() - t0 > cfg.pollBudgetMs) return fail('POLL_TIMEOUT');
655
+ if (polls >= maxPolls) return fail('POLL_TIMEOUT');
656
+ polls++;
657
+ await nap(cfg.pollIntervalMs);
658
+ if (signal?.aborted) return fail('TIMEOUT');
659
+ let polled = null;
660
+ let pollErr = null;
661
+ for (let attempt = 0; ; attempt++) {
662
+ if (signal?.aborted) return fail('TIMEOUT');
663
+ pollErr = null;
664
+ try {
665
+ polled = await callPhase1('openmotion_get_project', { projectId, exportJobId: jobId });
666
+ } catch (e) { pollErr = e; }
667
+ if (polled?.res?.ok) break;
668
+ try { await polled?.res?.body?.cancel?.(); } catch { /* 忽略 */ }
669
+ const status = polled?.res?.status ?? 0;
670
+ const retryable = pollErr !== null || status === 0 || status === 408 || status === 429 || status >= 500;
671
+ if (!retryable || attempt >= POLL_RETRY_DELAYS.length) {
672
+ if (pollErr) return fail(classifyError(pollErr, 'NETWORK'));
673
+ return fail('UNKNOWN', `查进度失败:接口返回 ${status || '未知'}`);
674
+ }
675
+ await nap(POLL_RETRY_DELAYS[attempt]);
676
+ }
677
+ const st = readPoll('openmotion', polled.json, {});
678
+ if (st.state === 'succeeded') {
679
+ downloadPath = st.url ?? `/api/exports/${encodeURIComponent(jobId)}/file`;
680
+ break;
681
+ }
682
+ if (st.state === 'failed') return fail('TASK_FAILED', st.error);
683
+ if (st.state === 'expired') return fail('TASK_EXPIRED');
684
+ }
685
+
686
+ let downloadUrl;
687
+ try {
688
+ const u = new URL(downloadPath, origin);
689
+ if (u.origin !== origin) return fail('DOWNLOAD_FAILED', '导出文件地址非本机同源');
690
+ downloadUrl = u.href;
691
+ } catch {
692
+ return fail('NO_URL');
693
+ }
694
+
695
+ const base = `video-${Date.now()}-${randomBytes(4).toString('hex')}`;
696
+ const partPath = join(outDir, `${base}.part`);
697
+ const finalPath = join(outDir, `${base}.mp4`);
698
+ let dlRes = null;
699
+ let fd = null;
700
+ let size = 0;
701
+ try {
702
+ dlRes = await fetchImpl(downloadUrl, {
703
+ method: 'GET',
704
+ redirect: 'error',
705
+ signal: timeoutSignal(Math.max(cfg.timeoutMs, DOWNLOAD_TIMEOUT_MIN), signal)
706
+ });
707
+ if (!dlRes || !dlRes.ok || !dlRes.body) return fail('DOWNLOAD_FAILED', `接口返回 ${dlRes?.status ?? '未知'}`);
708
+ const declared = Number(dlRes.headers?.get?.('content-length') ?? dlRes.headers?.['content-length']);
709
+ if (Number.isFinite(declared) && declared > cfg.maxBytes) return fail('TOO_LARGE', `声明 ${Math.round(declared / MB)}MB`);
710
+ fd = openSync(partPath, 'w');
711
+ size = await writeBody(dlRes.body, fd, cfg.maxBytes);
712
+ closeSync(fd);
713
+ fd = null;
714
+ let head = Buffer.alloc(0);
715
+ const hfd = openSync(partPath, 'r');
716
+ try {
717
+ head = Buffer.alloc(12);
718
+ const got = readSync(hfd, head, 0, 12, 0);
719
+ head = head.subarray(0, got);
720
+ } finally {
721
+ closeSync(hfd);
722
+ }
723
+ if (!isMp4Bytes(head)) return fail('BAD_VIDEO');
724
+ renameSync(partPath, finalPath);
725
+ } catch (e) {
726
+ return fail(classifyError(e, 'DOWNLOAD_FAILED'));
727
+ } finally {
728
+ try { await dlRes?.body?.cancel?.(); } catch { /* 已经关了 */ }
729
+ if (fd !== null) { try { closeSync(fd); } catch { /* 已经关了 */ } }
730
+ if (existsSync(partPath)) { try { unlinkSync(partPath); } catch { /* 删不掉就算了 */ } }
731
+ }
732
+ return { ok: true, file: resolve(finalPath), bytes: size, provider: 'openmotion', elapsedMs: clock() - t0 };
733
+ }
734
+
459
735
  export async function generateVideo(rawCfg, { prompt, outDir, fetchImpl = globalThis.fetch, sleep, now, signal, downloadImpl } = {}) {
460
736
  const cfg = videoGenConfig(rawCfg); // 归一化必须在这层做:漏了 pollBudgetMs 会让预算判断恒假 → 死循环
461
737
  const provider = cfg.provider;
@@ -479,7 +755,8 @@ export async function generateVideo(rawCfg, { prompt, outDir, fetchImpl = global
479
755
  let t0 = 0;
480
756
  try {
481
757
  if (!cfg.enabled) return fail('DISABLED');
482
- if (!cfg.baseURL || !cfg.apiKey || !cfg.model || !outDir || !String(prompt ?? '').trim()) return fail('NOT_CONFIGURED');
758
+ if (!outDir || !String(prompt ?? '').trim()) return fail('NOT_CONFIGURED');
759
+ if (provider !== 'openmotion' && (!cfg.baseURL || !cfg.apiKey || !cfg.model)) return fail('NOT_CONFIGURED');
483
760
  // 分辨率跟模型绑着:2K 只有 MiniMax-H3 支持。错配就别发出去让对方拒(提交是花钱的)
484
761
  if (provider === 'minimax' && !minimaxResolutionOk(cfg.model, cfg.resolution)) {
485
762
  return fail('NOT_CONFIGURED', `${cfg.model} 不支持 2K(只有 480P / 768P),把分辨率改成 768P`);
@@ -487,6 +764,9 @@ export async function generateVideo(rawCfg, { prompt, outDir, fetchImpl = global
487
764
  mkdirSync(outDir, { recursive: true });
488
765
  const free = statfsSync(outDir);
489
766
  if (Number(free.bavail) * Number(free.bsize) < FREE_MIN) return fail('NO_SPACE');
767
+ if (provider === 'openmotion') {
768
+ return await generateOpenMotionVideo(cfg, { prompt, outDir, fetchImpl, nap, clock, signal });
769
+ }
490
770
  t0 = clock();
491
771
 
492
772
  // 提交
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-fish-soul",
3
- "version": "0.18.16",
4
- "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.18.16)",
3
+ "version": "0.18.17",
4
+ "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.18.17)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
7
7
  "files": [