dsh-fish-soul 0.19.30 → 0.19.31

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.19.30**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.31**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -130,6 +130,12 @@ export function douyinConfigSchema(z) {
130
130
  perHour: z.number().default(4),
131
131
  replyChars: z.number().min(10).max(300).default(40),
132
132
  emoji: z.boolean().default(false)
133
+ }).default({}),
134
+ cli: z.object({ // 抖音开放 CLI(douyin-open-cli)混合驱动配置
135
+ socialBackend: z.string().default('browser'), // browser | hybrid
136
+ binaryPath: z.string().default('douyin-open-cli'),
137
+ authDir: z.string().default(''),
138
+ browseText: z.boolean().default(false)
133
139
  }).default({})
134
140
  }).default({});
135
141
  }
@@ -144,7 +144,7 @@ export class DouyinBrowser {
144
144
  * @param {import('./douyin-http.js').DouyinHttp} [deps.http] 纯 HTTP 客户端(http 模式用)
145
145
  * @param {object} [deps.timing] 页面操作的时间上限(eval / send / next 的总预算)
146
146
  */
147
- constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, frames, timing = {} }) {
147
+ constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, cli = null, frames, timing = {} }) {
148
148
  this.share = share ?? null;
149
149
  // #133:同上 —— 漏了这个参数兜底就是死代码。
150
150
  this.shareFallback = shareFallback ?? null;
@@ -163,6 +163,7 @@ export class DouyinBrowser {
163
163
  this.settleMs = settleMs;
164
164
  this.fetch = fetchImpl ?? ((...a) => fetch(...a));
165
165
  this.http = http ?? null; // 纯 HTTP 客户端(http 模式用;没有就退回浏览器)
166
+ this.cli = cli ?? null; // 可选:用 douyin-open-cli video text 补强视频口播/高质量文本
166
167
  this.running = false;
167
168
  this.httpBroken = false; // 这轮试过纯 HTTP 不行 → 退回浏览器
168
169
  this.described = new Map();
@@ -464,6 +465,8 @@ export class DouyinBrowser {
464
465
  imageCount: sum.imageCount,
465
466
  comments: (cm.ok ? cm.list : []).map((c) => ({ text: String(c.text ?? ''), author: String(c.user?.nickname ?? '') }))
466
467
  };
468
+ const cliText = await this.cliTextFor(v.id);
469
+ if (cliText !== '') v.ocr = v.ocr ? `${v.ocr};${cliText}` : cliText;
467
470
  // 抽帧看画面(默认关):九宫格 → 再让模型读成一句话,塞进这段感受里。
468
471
  // 和 B站 那条一个套路:拿不到就照旧只看文字,不影响她看完这条。
469
472
  const shot = await this.frameForWatch(d, v.id);
@@ -764,12 +767,25 @@ export class DouyinBrowser {
764
767
  const sum = extractWorkSummary(d, cm.ok ? cm.list : []);
765
768
  // 抽帧看画面(默认关,共用"自己刷视频"那个开关与每日配额):
766
769
  // 私信里分享的视频也该看得见画面,不能只给文案 + 热评(用户反馈 2026-11-25)。
770
+ const cliText = await this.cliTextFor(id);
767
771
  const shot = sum.imageCount > 0 ? '' : await this.frameForWatch(d, id);
768
772
  return `【抖音${sum.imageCount > 0 ? '图文' : '视频'}:${oneLine(sum.title, 120) || '(没有文案)'};作者 ${oneLine(sum.author, 20) || '未知'}`
769
773
  + (sum.imageCount > 0 ? `;共 ${sum.imageCount} 张图` : '')
770
774
  + (sum.music ? `;BGM:${oneLine(sum.music, 40)}` : '')
771
775
  + (sum.ocr ? `;画面文字:${oneLine(sum.ocr, 80)}` : '')
776
+ + (cliText ? `;视频文本:${oneLine(cliText, 120)}` : '')
772
777
  + (shot ? `;画面:${shot}` : '')
773
778
  + (sum.topComments.length ? `;热评:${sum.topComments.join(' / ')}` : '') + '】';
774
779
  }
780
+
781
+ /** 开了 douyin.cli.browseText 时调 CLI 拿官方高质量文本;失败静默退回空串,不阻断看视频。 */
782
+ async cliTextFor(id) {
783
+ if (!this.cli || this.getConfig()?.cli?.browseText !== true) return '';
784
+ try {
785
+ const r = await this.cli.videoText(id);
786
+ return r?.ok ? oneLine(r.text, 200) : '';
787
+ } catch {
788
+ return '';
789
+ }
790
+ }
775
791
  }
@@ -0,0 +1,474 @@
1
+ /**
2
+ * douyin-cli.js —— 抖音开放 CLI(douyin-open-cli)底层执行与协议适配层。
3
+ *
4
+ * 设计要点:
5
+ * 1. 只用 execFile(绝不走 shell),防止文案/标题里的特殊字符引发命令注入或 Windows 转义错乱;
6
+ * 2. 复杂 JSON 写无 BOM 的临时 UTF-8 文件,通过 `--data @<file>` 传入并在 finally 清理;
7
+ * 3. 用 Node 22 原生 `JSON.parse(raw, reviver)` 的 `context.source` 保留超过 Number.MAX_SAFE_INTEGER 的
8
+ * 64 位整数(抖音 19 位 item_id / comment_id / uid),避免精度截断;
9
+ * 4. 严格分离 stdout(业务 JSON)与 stderr(自动升级提醒 / 诊断日志),不把升级告警当成业务失败;
10
+ * 5. 统一区分「未发出去」(NOT_ATTEMPTED)与「结果不明」(ATTEMPTED_UNKNOWN),对齐 DouyinPostJobs 与防重发护栏。
11
+ */
12
+ import { execFile as execFileCb } from 'node:child_process';
13
+ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { promisify } from 'node:util';
17
+ import { WRITE_NOT_ATTEMPTED, WRITE_ATTEMPTED_UNKNOWN } from './channels/vendor/douyin-bridge/douyin-comment.js';
18
+
19
+ const execFileAsync = promisify(execFileCb);
20
+
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const UPLOAD_TIMEOUT_MS = 180_000;
23
+ const MAX_BUFFER_BYTES = 16 * 1024 * 1024;
24
+ const SAFE_INT_RE = /^-?\d+$/;
25
+
26
+ const AUTH_ERROR_CODES = new Set([
27
+ 'AUTH_REQUIRED',
28
+ 'AUTH_REFRESH_FAILED',
29
+ 'SCOPE_INSUFFICIENT',
30
+ 'TOKEN_MISSING',
31
+ 'CREDENTIALS_MISSING',
32
+ 'REAUTHORIZATION_REQUIRED'
33
+ ]);
34
+
35
+ const UNKNOWN_WRITE_CODES = new Set([
36
+ 'WRITE_OUTCOME_UNKNOWN',
37
+ 'REQUEST_TIMEOUT',
38
+ 'REQUEST_CANCELED'
39
+ ]);
40
+
41
+ /** 保留超过安全整数范围的 64 位整数(抖音 19 位作品/评论/用户 ID)为原始字符串。 */
42
+ export function parseCliJson(raw) {
43
+ const text = String(raw ?? '').trim();
44
+ if (text === '') return null;
45
+ return JSON.parse(text, (_key, value, context) => {
46
+ if (typeof value === 'number' && context && typeof context.source === 'string') {
47
+ const src = context.source.trim();
48
+ if (SAFE_INT_RE.test(src) && !Number.isSafeInteger(value)) return src;
49
+ }
50
+ return value;
51
+ });
52
+ }
53
+
54
+ /** 提取 CLI 返回体里的业务数据(兼容直出对象与 { err_no, data } 网关包装)。 */
55
+ function unwrapData(parsed) {
56
+ if (!parsed || typeof parsed !== 'object') return null;
57
+ const d = parsed.data;
58
+ if (d && typeof d === 'object' && d.data && typeof d.data === 'object' && ('err_no' in d || 'error_code' in d)) {
59
+ return d.data;
60
+ }
61
+ return d ?? parsed;
62
+ }
63
+
64
+ /** 从 CLI 失败对象或异常中提取标准化错误码与原因。 */
65
+ function extractCliError(parsed, err) {
66
+ const eObj = parsed?.error && typeof parsed.error === 'object' ? parsed.error : null;
67
+ const rawCode = String(eObj?.code ?? parsed?.code ?? parsed?.error_code ?? err?.code ?? '').trim();
68
+ const msg = String(
69
+ eObj?.message ?? eObj?.description ?? parsed?.message ?? parsed?.err_msg ?? err?.message ?? 'CLI 执行失败'
70
+ ).trim();
71
+ return { rawCode, msg };
72
+ }
73
+
74
+ /** 把字符串或数字安全转为非空 ID 字符串(兼容 19 位大整数)。 */
75
+ function idStr(v) {
76
+ if (v === null || v === undefined) return '';
77
+ const s = String(v).trim();
78
+ return s === '0' ? '' : s;
79
+ }
80
+
81
+ /** 构造仅包含正整数文本的 JSON(供 `--data @FILE` 传 64 位整数,避免 JS Number 精度丢失)。 */
82
+ export function buildCommentReplyJson({ itemId, replyId, replyToReplyId, text }) {
83
+ const parts = [`"ItemId":${String(itemId).trim()}`];
84
+ if (replyId) parts.push(`"ReplyId":${String(replyId).trim()}`);
85
+ if (replyToReplyId) parts.push(`"ReplyToReplyId":${String(replyToReplyId).trim()}`);
86
+ parts.push(`"Text":${JSON.stringify(String(text ?? ''))}`);
87
+ return `{${parts.join(',')}}`;
88
+ }
89
+
90
+ /** 构造评论对象(对齐 DouyinSocial 的 listCommentsApi 形状)。 */
91
+ function normalizeCommentItem(raw) {
92
+ if (!raw || typeof raw !== 'object') return null;
93
+ const cid = idStr(raw.cid ?? raw.comment_id ?? raw.CommentId ?? raw.id);
94
+ const user = raw.user && typeof raw.user === 'object' ? raw.user : {};
95
+ const uid = idStr(raw.uid ?? raw.user_id ?? user.uid ?? user.user_id);
96
+ const author = String(raw.author ?? raw.nickname ?? user.nickname ?? user.name ?? '').trim();
97
+ const content = String(raw.text ?? raw.content ?? raw.Text ?? '').trim();
98
+ const createTime = Number(raw.create_time ?? raw.createTime ?? raw.CreateTime ?? 0) || 0;
99
+ const replyTotal = Number(raw.reply_comment_total ?? raw.replyTotal ?? raw.ReplyCount ?? 0) || 0;
100
+ const labelType = Number(raw.label_type ?? raw.labelType ?? 0) || 0;
101
+ const hasImage = Boolean(raw.image_list?.length || raw.sticker || raw.has_image || raw.hasImage);
102
+ const replyComment = Array.isArray(raw.reply_comment ?? raw.replyComment)
103
+ ? (raw.reply_comment ?? raw.replyComment).map(normalizeCommentItem).filter(Boolean)
104
+ : [];
105
+ return {
106
+ cid,
107
+ uid,
108
+ author,
109
+ content,
110
+ createTime,
111
+ replyTotal,
112
+ labelType,
113
+ hasImage,
114
+ isAuthor: labelType === 1 || raw.is_author === true || raw.isAuthor === true,
115
+ canReply: cid !== '',
116
+ replyComment
117
+ };
118
+ }
119
+
120
+ /** 构造作品列表项(对齐 DouyinSocial 的 listWorks 形状)。 */
121
+ function normalizeWorkItem(raw) {
122
+ if (!raw || typeof raw !== 'object') return null;
123
+ const id = idStr(raw.item_id ?? raw.aweme_id ?? raw.video_id ?? raw.ItemId ?? raw.id);
124
+ if (!id) return null;
125
+ const title = String(raw.title ?? raw.desc ?? raw.Desc ?? '').trim();
126
+ const mediaType = Number(raw.aweme_type ?? raw.media_type ?? 0);
127
+ const kind = mediaType === 68 || raw.kind === 'note' ? 'note' : 'video';
128
+ return { id, kind, title, href: `https://www.douyin.com/video/${id}` };
129
+ }
130
+
131
+ export class DouyinCli {
132
+ /**
133
+ * @param {object} [opts]
134
+ * @param {() => object} [opts.getConfig] 返回 config.douyin.cli
135
+ * @param {(level: string, msg: string) => void} [opts.log]
136
+ * @param {(file: string, args: string[], options: object) => Promise<{stdout: string, stderr: string}>} [opts.execFileImpl]
137
+ */
138
+ constructor({ getConfig, log, execFileImpl } = {}) {
139
+ this.getConfig = typeof getConfig === 'function' ? getConfig : () => ({});
140
+ this.log = typeof log === 'function' ? log : () => {};
141
+ this.execFileImpl = execFileImpl ?? execFileAsync;
142
+ }
143
+
144
+ cfg() {
145
+ const raw = this.getConfig() ?? {};
146
+ return {
147
+ socialBackend: raw.socialBackend === 'hybrid' ? 'hybrid' : 'browser',
148
+ binaryPath: String(raw.binaryPath ?? '').trim() || 'douyin-open-cli',
149
+ authDir: String(raw.authDir ?? '').trim(),
150
+ browseText: raw.browseText === true
151
+ };
152
+ }
153
+
154
+ /**
155
+ * 执行一条 douyin-open-cli 子命令。
156
+ * @param {string[]} args
157
+ * @param {object} [opts]
158
+ * @param {number} [opts.timeoutMs]
159
+ * @param {boolean} [opts.isWrite]
160
+ * @param {string|object|null} [opts.dataPayload] 传给 `--data @FILE` 的无 BOM UTF-8 内容
161
+ */
162
+ async exec(args, { timeoutMs = DEFAULT_TIMEOUT_MS, isWrite = false, dataPayload = null } = {}) {
163
+ const { binaryPath, authDir } = this.cfg();
164
+ const finalArgs = [...args];
165
+ let tempDir = '';
166
+ if (dataPayload !== null && dataPayload !== undefined) {
167
+ tempDir = mkdtempSync(join(tmpdir(), 'fish-soul-dycli-'));
168
+ const reqPath = join(tempDir, 'request.json');
169
+ const body = typeof dataPayload === 'string' ? dataPayload : JSON.stringify(dataPayload);
170
+ writeFileSync(reqPath, body, { encoding: 'utf8' });
171
+ finalArgs.push('--data', `@${reqPath}`);
172
+ }
173
+ if (!finalArgs.includes('--output')) finalArgs.push('--output', 'json');
174
+
175
+ const env = { ...process.env };
176
+ if (authDir !== '') env.DOUYIN_OPEN_CLI_AUTH_DIR = authDir;
177
+
178
+ try {
179
+ const { stdout, stderr } = await this.execFileImpl(binaryPath, finalArgs, {
180
+ timeout: timeoutMs,
181
+ maxBuffer: MAX_BUFFER_BYTES,
182
+ windowsHide: true,
183
+ env
184
+ });
185
+ const errLine = String(stderr ?? '').trim();
186
+ if (errLine !== '') this.log('info', `[fish-soul] douyin-open-cli stderr: ${errLine.slice(0, 200)}`);
187
+
188
+ let parsed;
189
+ try {
190
+ parsed = parseCliJson(stdout);
191
+ } catch (parseErr) {
192
+ const msg = `CLI 返回非 JSON:${parseErr instanceof Error ? parseErr.message : String(parseErr)}`;
193
+ return {
194
+ ok: false,
195
+ code: isWrite ? 'WRITE_UNKNOWN' : 'INVALID_RESPONSE',
196
+ writeState: isWrite ? WRITE_ATTEMPTED_UNKNOWN : WRITE_NOT_ATTEMPTED,
197
+ error: msg
198
+ };
199
+ }
200
+
201
+ if (!parsed || typeof parsed !== 'object') {
202
+ return {
203
+ ok: false,
204
+ code: isWrite ? 'WRITE_UNKNOWN' : 'INVALID_RESPONSE',
205
+ writeState: isWrite ? WRITE_ATTEMPTED_UNKNOWN : WRITE_NOT_ATTEMPTED,
206
+ error: 'CLI 返回空内容'
207
+ };
208
+ }
209
+
210
+ if (parsed.ok === false) {
211
+ const { rawCode, msg } = extractCliError(parsed, null);
212
+ if (AUTH_ERROR_CODES.has(rawCode)) {
213
+ return { ok: false, code: 'AUTH_REQUIRED', rawCode, writeState: WRITE_NOT_ATTEMPTED, error: msg, parsed };
214
+ }
215
+ if (isWrite && UNKNOWN_WRITE_CODES.has(rawCode)) {
216
+ return { ok: false, code: 'WRITE_UNKNOWN', rawCode, writeState: WRITE_ATTEMPTED_UNKNOWN, error: msg, parsed };
217
+ }
218
+ return {
219
+ ok: false,
220
+ code: rawCode || 'CLI_ERROR',
221
+ rawCode,
222
+ writeState: WRITE_NOT_ATTEMPTED,
223
+ error: msg,
224
+ parsed
225
+ };
226
+ }
227
+
228
+ return { ok: true, parsed, data: unwrapData(parsed) };
229
+ } catch (err) {
230
+ if (err?.code === 'ENOENT') {
231
+ return {
232
+ ok: false,
233
+ code: 'CLI_NOT_FOUND',
234
+ writeState: WRITE_NOT_ATTEMPTED,
235
+ error: `找不到 ${binaryPath},请先安装 douyin-open-cli`
236
+ };
237
+ }
238
+ let parsed = null;
239
+ if (err?.stdout) {
240
+ try { parsed = parseCliJson(err.stdout); } catch { /* stdout 不是有效 JSON,按进程错误分类 */ }
241
+ }
242
+ const { rawCode, msg } = extractCliError(parsed, err);
243
+ if (AUTH_ERROR_CODES.has(rawCode)) {
244
+ return { ok: false, code: 'AUTH_REQUIRED', rawCode, writeState: WRITE_NOT_ATTEMPTED, error: msg, parsed };
245
+ }
246
+ const isTimeoutOrKilled = Boolean(err?.killed || err?.signal === 'SIGTERM' || err?.code === 'ETIMEDOUT' || UNKNOWN_WRITE_CODES.has(rawCode));
247
+ if (isWrite && isTimeoutOrKilled) {
248
+ return {
249
+ ok: false,
250
+ code: 'WRITE_UNKNOWN',
251
+ rawCode: rawCode || 'REQUEST_TIMEOUT',
252
+ writeState: WRITE_ATTEMPTED_UNKNOWN,
253
+ error: `写操作超时或结果不明:${msg}`,
254
+ parsed
255
+ };
256
+ }
257
+ return {
258
+ ok: false,
259
+ code: rawCode || (isTimeoutOrKilled ? 'TIMEOUT' : 'CLI_ERROR'),
260
+ rawCode,
261
+ writeState: WRITE_NOT_ATTEMPTED,
262
+ error: msg,
263
+ parsed
264
+ };
265
+ } finally {
266
+ if (tempDir !== '') {
267
+ try { rmSync(tempDir, { recursive: true, force: true }); } catch { /* 临时目录清理失败不影响主结果 */ }
268
+ }
269
+ }
270
+ }
271
+
272
+ /** 检查本地登录态与 scope 覆盖情况(不触发网络续期或扫码)。 */
273
+ async authStatus() {
274
+ const res = await this.exec(['auth', 'status']);
275
+ if (!res.ok) return { ok: false, loggedIn: false, code: res.code, error: res.error };
276
+ const d = res.data ?? {};
277
+ const loggedIn = d.logged_in === true || d.credential_status === 'valid';
278
+ const missingScopes = Array.isArray(d.missing_scopes) ? d.missing_scopes.map(String) : [];
279
+ return {
280
+ ok: true,
281
+ loggedIn,
282
+ credentialStatus: String(d.credential_status ?? ''),
283
+ openId: String(d.open_id ?? ''),
284
+ expiresAt: d.expires_at ?? null,
285
+ tokenExpired: d.token_expired === true,
286
+ missingScopes,
287
+ reauthRequired: d.reauthorization_required === true
288
+ };
289
+ }
290
+
291
+ /** 判断给定 authStatus 是否覆盖目标 scope。 */
292
+ static hasScope(status, scope) {
293
+ if (!status?.ok || !status.loggedIn) return false;
294
+ if (!scope) return true;
295
+ return !Array.isArray(status.missingScopes) || !status.missingScopes.includes(scope);
296
+ }
297
+
298
+ /** 发起非阻塞扫码登录,返回二维码图片 DataURL(如存在)与轮询建议。 */
299
+ async authLoginBegin({ force = false } = {}) {
300
+ const args = ['auth', 'login', '--begin'];
301
+ if (force) args.push('--force');
302
+ const res = await this.exec(args, { timeoutMs: 45_000 });
303
+ if (!res.ok) return { ok: false, code: res.code, error: res.error };
304
+ const d = res.data ?? {};
305
+ const qrImagePath = String(d.qr_image_path ?? '').trim();
306
+ let qrDataUrl = '';
307
+ if (qrImagePath !== '' && /\.png$/i.test(qrImagePath)) {
308
+ try {
309
+ const st = statSync(qrImagePath);
310
+ if (st.isFile() && st.size > 0 && st.size <= 2 * 1024 * 1024) {
311
+ const buf = readFileSync(qrImagePath);
312
+ qrDataUrl = `data:image/png;base64,${buf.toString('base64')}`;
313
+ }
314
+ } catch { /* 读取二维码文件失败时回退 verification_url */ }
315
+ }
316
+ return {
317
+ ok: true,
318
+ alreadyLoggedIn: d.logged_in === true || d.status === 'logged_in',
319
+ status: String(d.status ?? (qrImagePath ? 'pending' : 'logged_in')),
320
+ qrImagePath,
321
+ qrDataUrl,
322
+ verificationUrl: String(d.verification_url ?? ''),
323
+ retryAfterSeconds: Number(d.retry_after_seconds ?? 3) || 3,
324
+ expiresAt: d.expires_at ?? null
325
+ };
326
+ }
327
+
328
+ /** 轮询一次待确认的扫码登录状态。 */
329
+ async authLoginComplete() {
330
+ const res = await this.exec(['auth', 'login', '--complete'], { timeoutMs: 30_000 });
331
+ if (!res.ok) return { ok: false, status: 'failed', code: res.code, error: res.error };
332
+ const d = res.data ?? {};
333
+ const status = d.logged_in === true || d.status === 'logged_in' || d.status === 'completed'
334
+ ? 'logged_in'
335
+ : (d.status === 'pending' ? 'pending' : 'failed');
336
+ return {
337
+ ok: true,
338
+ status,
339
+ loggedIn: status === 'logged_in',
340
+ retryAfterSeconds: Number(d.retry_after_seconds ?? 3) || 3,
341
+ openId: String(d.open_id ?? '')
342
+ };
343
+ }
344
+
345
+ /** 查询自己的作品列表。 */
346
+ async videoList({ count = 3 } = {}) {
347
+ const n = Math.min(30, Math.max(1, Math.floor(Number(count) || 3)));
348
+ const res = await this.exec(['video', 'list', '--count', String(n)]);
349
+ if (!res.ok) return { ok: false, works: [], code: res.code, error: res.error };
350
+ const d = res.data ?? {};
351
+ const rawList = Array.isArray(d.list) ? d.list
352
+ : Array.isArray(d.videos) ? d.videos
353
+ : Array.isArray(d.item_list) ? d.item_list
354
+ : Array.isArray(d.aweme_list) ? d.aweme_list
355
+ : [];
356
+ return { ok: true, works: rawList.map(normalizeWorkItem).filter(Boolean) };
357
+ }
358
+
359
+ /** 获取作品高质量文本(口播 / 字幕 / 摘要),用于补强刷视频内容理解。 */
360
+ async videoText(videoId) {
361
+ const id = idStr(videoId);
362
+ if (!id) return { ok: false, text: '', code: 'INVALID_ID', error: '缺少作品 ID' };
363
+ const res = await this.exec(['video', 'text', '--video-id', id], { timeoutMs: 15_000 });
364
+ if (!res.ok) return { ok: false, text: '', code: res.code, error: res.error };
365
+ const d = res.data ?? {};
366
+ const text = String(d.high_quality_text ?? d.text ?? '').trim();
367
+ return { ok: text !== '', text };
368
+ }
369
+
370
+ /** 上传本地视频,返回加密 video_id(非作品 ID)。 */
371
+ async videoUpload(filePath) {
372
+ const res = await this.exec(['video', 'upload', '--file', String(filePath), '--yes'], {
373
+ timeoutMs: UPLOAD_TIMEOUT_MS,
374
+ isWrite: false
375
+ });
376
+ if (!res.ok) return { ok: false, code: res.code, error: res.error };
377
+ const d = res.data ?? {};
378
+ const videoId = String(d.video?.video_id ?? d.video_id ?? '').trim();
379
+ if (!videoId) return { ok: false, code: 'UPLOAD_NO_ID', error: '上传返回缺少 video_id' };
380
+ return { ok: true, videoId };
381
+ }
382
+
383
+ /** 用已上传的加密 video_id 正式投稿发布视频。 */
384
+ async videoPublish({ videoId, title, privateStatus = 0 }) {
385
+ const payload = {
386
+ video_id: String(videoId),
387
+ text: String(title ?? '').slice(0, 1000),
388
+ private_status: Number(privateStatus) || 0,
389
+ publish_way: 0
390
+ };
391
+ const res = await this.exec(['video', 'publish', '--yes'], {
392
+ timeoutMs: 60_000,
393
+ isWrite: true,
394
+ dataPayload: payload
395
+ });
396
+ if (!res.ok) {
397
+ return { ok: false, code: res.code, writeState: res.writeState, error: res.error };
398
+ }
399
+ const d = res.data ?? {};
400
+ const workId = idStr(d.item_id ?? d.video_id ?? d.aweme_id);
401
+ return { ok: true, workId };
402
+ }
403
+
404
+ /** 查询作品一级评论列表。 */
405
+ async commentList(videoId, { pageSize = 20, pageToken = '0' } = {}) {
406
+ const id = idStr(videoId);
407
+ if (!id) return { ok: false, comments: [], code: 'INVALID_ID', error: '缺少作品 ID' };
408
+ const size = Math.min(50, Math.max(1, Math.floor(Number(pageSize) || 20)));
409
+ const res = await this.exec([
410
+ 'comment', 'list',
411
+ '--video-id', id,
412
+ '--page-size', String(size),
413
+ '--page-token', String(pageToken ?? '0')
414
+ ]);
415
+ if (!res.ok) return { ok: false, comments: [], code: res.code, error: res.error };
416
+ const d = res.data ?? {};
417
+ const rawList = Array.isArray(d.comments) ? d.comments
418
+ : Array.isArray(d.list) ? d.list
419
+ : Array.isArray(d.comment_list) ? d.comment_list
420
+ : [];
421
+ return { ok: true, comments: rawList.map(normalizeCommentItem).filter(Boolean) };
422
+ }
423
+
424
+ /** 查询某条评论的回复列表。 */
425
+ async commentReplyList(videoId, commentId, { pageSize = 20, pageToken = '0' } = {}) {
426
+ const vid = idStr(videoId);
427
+ const cid = idStr(commentId);
428
+ if (!vid || !cid) return { ok: false, comments: [], code: 'INVALID_ID', error: '缺少作品或评论 ID' };
429
+ const size = Math.min(50, Math.max(1, Math.floor(Number(pageSize) || 20)));
430
+ const res = await this.exec([
431
+ 'comment', 'reply-list',
432
+ '--video-id', vid,
433
+ '--comment-id', cid,
434
+ '--page-size', String(size),
435
+ '--page-token', String(pageToken ?? '0')
436
+ ]);
437
+ if (!res.ok) return { ok: false, comments: [], code: res.code, error: res.error };
438
+ const d = res.data ?? {};
439
+ const rawList = Array.isArray(d.comments) ? d.comments
440
+ : Array.isArray(d.list) ? d.list
441
+ : Array.isArray(d.reply_list) ? d.reply_list
442
+ : [];
443
+ return { ok: true, comments: rawList.map(normalizeCommentItem).filter(Boolean) };
444
+ }
445
+
446
+ /** 回复评论(支持一级评论和二级楼中楼)。 */
447
+ async commentReply({ itemId, replyId, replyToReplyId, text }) {
448
+ const iid = idStr(itemId);
449
+ const rid = idStr(replyId);
450
+ const rtrid = idStr(replyToReplyId);
451
+ if (!iid || !rid || !/^\d+$/.test(iid) || !/^\d+$/.test(rid)) {
452
+ return { ok: false, code: 'INVALID_ID', writeState: WRITE_NOT_ATTEMPTED, error: '无效的作品或评论 ID' };
453
+ }
454
+ if (rtrid && !/^\d+$/.test(rtrid)) {
455
+ return { ok: false, code: 'INVALID_ID', writeState: WRITE_NOT_ATTEMPTED, error: '无效的二级评论 ID' };
456
+ }
457
+ const cleanText = String(text ?? '').trim();
458
+ if (!cleanText) {
459
+ return { ok: false, code: 'EMPTY_TEXT', writeState: WRITE_NOT_ATTEMPTED, error: '评论正文为空' };
460
+ }
461
+ const jsonBody = buildCommentReplyJson({ itemId: iid, replyId: rid, replyToReplyId: rtrid, text: cleanText });
462
+ const res = await this.exec(['comment', 'reply', '--yes'], {
463
+ timeoutMs: 30_000,
464
+ isWrite: true,
465
+ dataPayload: jsonBody
466
+ });
467
+ if (!res.ok) {
468
+ return { ok: false, code: res.code, writeState: res.writeState, error: res.error };
469
+ }
470
+ const d = res.data ?? {};
471
+ const cid = idStr(d.comment_id ?? d.cid ?? d.CommentId);
472
+ return { ok: true, cid };
473
+ }
474
+ }
@@ -41,8 +41,9 @@ export class DouyinPostJobs {
41
41
  const r=this.db.prepare("UPDATE douyin_post_job SET status='confirmed',error='',updated_at=? WHERE id=? AND status='submitting'").run(Date.now(),id);
42
42
  if (Number(r.changes)!==1) throw Error('发布任务状态异常,需核实');
43
43
  }
44
- fail(id, error) {
45
- this.db.prepare("UPDATE douyin_post_job SET status=CASE status WHEN 'submitting' THEN 'unknown' ELSE 'failed' END, error=?,updated_at=? WHERE id=? AND status IN ('preparing','submitting')").run(String(error).slice(0,300),Date.now(),id);
44
+ fail(id, error, { notAttempted = false } = {}) {
45
+ const nextStatus = notAttempted ? "'failed'" : "CASE status WHEN 'submitting' THEN 'unknown' ELSE 'failed' END";
46
+ this.db.prepare(`UPDATE douyin_post_job SET status=${nextStatus}, error=?,updated_at=? WHERE id=? AND status IN ('preparing','submitting')`).run(String(error).slice(0,300),Date.now(),id);
46
47
  }
47
48
  resolvePublished(id) {
48
49
  return Number(this.db.prepare("UPDATE douyin_post_job SET status='confirmed_manual',error='用户核实已发布',updated_at=? WHERE id=? AND status='unknown'").run(Date.now(),id).changes) === 1;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * douyin-social-cli.js —— 基于 douyin-open-cli 的社交驱动与混合路由适配器。
3
+ *
4
+ * 混合架构分工:
5
+ * - 发短视频(upload + publish)与作品评论轮询/回复 → 走官方 douyin-open-cli(免浏览器锁、免创作者中心登录、免 DOM 改版/短信风控);
6
+ * - 发图文(文字卡片 + 自动挑推荐 BGM)→ 继续走专用浏览器驱动 douyinSocialDriver;
7
+ * - 带图片的评论回复(_stickers 表情包):若浏览器驱动可用且在线,自动委托给浏览器接口发图,否则降级纯文字走 CLI。
8
+ */
9
+ import { existsSync, statSync } from 'node:fs';
10
+ import { DouyinCli } from './douyin-cli.js';
11
+ import { WRITE_NOT_ATTEMPTED } from './channels/vendor/douyin-bridge/douyin-comment.js';
12
+
13
+ /**
14
+ * 构建纯 CLI 社交驱动(只负责发短视频与评论轮询/回复)。
15
+ * @param {DouyinCli} cli
16
+ * @param {object} [opts]
17
+ * @param {(level: string, msg: string) => void} [opts.log]
18
+ */
19
+ export function douyinSocialCliDriver(cli, { log } = {}) {
20
+ const logger = typeof log === 'function' ? log : () => {};
21
+ let stagedVideo = null;
22
+
23
+ return {
24
+ kind: 'cli',
25
+ videoNeedsBrowserLock: false,
26
+ commentsNeedBrowserLock: false,
27
+
28
+ /** 在调付费视频生成之前检查 CLI 登录态和 video.create 权限,避免白花钱。 */
29
+ async checkVideoAuth() {
30
+ let st = await cli.authStatus();
31
+ // auth status 只读本地凭证、不触发 refresh_token 续期;若仅 access_token 过期且无需重授权,先用轻量只读命令触发自动续期再复查。
32
+ if (st.ok && !st.loggedIn && st.tokenExpired && !st.reauthRequired) {
33
+ await cli.videoList({ count: 1 });
34
+ st = await cli.authStatus();
35
+ }
36
+ if (!st.ok) {
37
+ return { ok: false, code: st.code === 'CLI_NOT_FOUND' ? 'CLI_NOT_FOUND' : 'NOT_LOGGED_IN', error: st.error || '抖音 CLI 未就绪' };
38
+ }
39
+ if (!st.loggedIn) {
40
+ return { ok: false, code: 'NOT_LOGGED_IN', error: '抖音开放 CLI 还没扫码登录,请先调用 /douyin/cli/login/begin 或在终端运行 douyin-open-cli auth login 完成扫码授权' };
41
+ }
42
+ if (!DouyinCli.hasScope(st, 'video.create')) {
43
+ return { ok: false, code: 'NOT_LOGGED_IN', error: '抖音开放 CLI 缺少 video.create 投稿权限,请重新扫码授权' };
44
+ }
45
+ return { ok: true };
46
+ },
47
+
48
+ async prepareVideo({ title, text, file }) {
49
+ const filePath = String(file ?? '').trim();
50
+ let validFile = false;
51
+ try { validFile = filePath !== '' && existsSync(filePath) && statSync(filePath).isFile(); } catch { validFile = false; }
52
+ if (!validFile) {
53
+ stagedVideo = null;
54
+ return { ok: false, code: 'FILE_MISSING', error: '找不到刚生成的视频文件' };
55
+ }
56
+ const caption = String(text || title || '').trim();
57
+ stagedVideo = { file: filePath, title: caption };
58
+ return { ok: true };
59
+ },
60
+
61
+ async publishVideo({ beforeSubmit } = {}) {
62
+ if (!stagedVideo) return { ok: false, code: 'NOT_PREPARED', error: '没有待发布的视频' };
63
+ const { file, title } = stagedVideo;
64
+ stagedVideo = null;
65
+
66
+ // 第一步:上传视频拿加密 video_id(失败尚未触发投稿,不调用 beforeSubmit,不落 unknown)
67
+ const up = await cli.videoUpload(file);
68
+ if (!up.ok) {
69
+ const code = up.code === 'AUTH_REQUIRED' ? 'NOT_LOGGED_IN' : (up.code || 'UPLOAD_FAILED');
70
+ return { ok: false, code, error: `CLI 上传视频失败:${up.error}` };
71
+ }
72
+
73
+ // 第二步:真正提交投稿前进入 submitting 状态,对齐 DouyinPostJobs 防重发状态机
74
+ beforeSubmit?.();
75
+ const pub = await cli.videoPublish({ videoId: up.videoId, title, privateStatus: 0 });
76
+ if (!pub.ok) {
77
+ logger('warn', `[fish-soul] douyin-open-cli 视频投稿失败(${pub.code}):${pub.error}`);
78
+ const code = pub.code === 'AUTH_REQUIRED' ? 'NOT_LOGGED_IN' : pub.code;
79
+ return { ok: false, code, writeState: pub.writeState, error: pub.error };
80
+ }
81
+ return { ok: true, workId: pub.workId || '' };
82
+ },
83
+
84
+ async listWorks(limit = 3) {
85
+ const res = await cli.videoList({ count: limit });
86
+ if (!res.ok) {
87
+ logger('warn', `[fish-soul] douyin-open-cli 拉作品列表失败(${res.code}):${res.error}`);
88
+ return [];
89
+ }
90
+ return res.works.slice(0, limit);
91
+ },
92
+
93
+ async openWork() {
94
+ return { ok: true };
95
+ },
96
+
97
+ async listCommentsApi(videoId) {
98
+ const res = await cli.commentList(videoId, { pageSize: 20 });
99
+ if (!res.ok) {
100
+ logger('warn', `[fish-soul] douyin-open-cli 拉评论失败(${res.code}):${res.error}`);
101
+ return [];
102
+ }
103
+ return res.comments;
104
+ },
105
+
106
+ async listComments() {
107
+ return [];
108
+ },
109
+
110
+ async listCommentReplies(videoId, cid) {
111
+ const res = await cli.commentReplyList(videoId, cid, { pageSize: 20 });
112
+ if (!res.ok) return [];
113
+ return res.comments;
114
+ },
115
+
116
+ async emojiCodes() {
117
+ return [];
118
+ },
119
+
120
+ async replyApi({ awemeId, cid, replyToReplyId, text }, { onBeforeWrite } = {}) {
121
+ const cleanText = String(text ?? '').trim();
122
+ if (!cleanText) {
123
+ return { ok: false, code: 'EMPTY_TEXT', writeState: WRITE_NOT_ATTEMPTED, error: 'CLI 评论不支持纯图片或空正文' };
124
+ }
125
+ onBeforeWrite?.();
126
+ const res = await cli.commentReply({
127
+ itemId: awemeId,
128
+ replyId: cid,
129
+ replyToReplyId,
130
+ text: cleanText
131
+ });
132
+ if (!res.ok) {
133
+ return { ok: false, code: res.code, writeState: res.writeState, error: res.error };
134
+ }
135
+ return { ok: true, cid: res.cid };
136
+ },
137
+
138
+ async reply() {
139
+ return { ok: false, code: 'NO_DOM_IN_CLI', error: 'CLI 模式不走页面点击回复' };
140
+ }
141
+ };
142
+ }
143
+
144
+ /**
145
+ * 混合驱动工厂:按实时配置在 browser 与 hybrid(CLI 视频+评论 + 浏览器图文)之间路由。
146
+ * @param {object} opts
147
+ * @param {object} opts.browserDriver 原 douyinSocialDriver(host)
148
+ * @param {object} opts.cliDriver douyinSocialCliDriver(cli)
149
+ * @param {() => string} opts.getMode 返回 'browser' | 'hybrid'
150
+ * @param {() => boolean} [opts.browserReady] 浏览器是否已运行且登录(用于带图评论降级)
151
+ */
152
+ export function hybridDouyinSocialDriver({ browserDriver, cliDriver, getMode, browserReady }) {
153
+ const useCli = () => getMode?.() === 'hybrid';
154
+ const canBrowser = () => typeof browserReady === 'function' && browserReady() === true;
155
+
156
+ return {
157
+ get videoNeedsBrowserLock() { return !useCli(); },
158
+ get commentsNeedBrowserLock() { return !useCli(); },
159
+ get cliActive() { return useCli(); },
160
+ replyNeedsBrowserLock: (images) => useCli() && Array.isArray(images) && images.length > 0 && canBrowser() && typeof browserDriver.replyApi === 'function',
161
+
162
+ // ── 图文与配乐:始终走专用浏览器驱动 ──
163
+ prepareNote: (...a) => browserDriver.prepareNote(...a),
164
+ listRecommendedMusic: (...a) => browserDriver.listRecommendedMusic?.(...a),
165
+ publishNote: (...a) => browserDriver.publishNote(...a),
166
+ closeMusicPanel: (...a) => browserDriver.closeMusicPanel?.(...a),
167
+ readTopWorkId: (...a) => browserDriver.readTopWorkId?.(...a),
168
+ emojiCodes: (...a) => (useCli() ? cliDriver.emojiCodes(...a) : browserDriver.emojiCodes(...a)),
169
+
170
+ // ── 发短视频:hybrid 走 CLI,browser 走原驱动 ──
171
+ checkVideoAuth: () => (useCli() ? cliDriver.checkVideoAuth() : Promise.resolve({ ok: true, fallbackCookieCheck: true })),
172
+ prepareVideo: (...a) => (useCli() ? cliDriver.prepareVideo(...a) : browserDriver.prepareVideo(...a)),
173
+ publishVideo: (...a) => (useCli() ? cliDriver.publishVideo(...a) : browserDriver.publishVideo(...a)),
174
+
175
+ // ── 作品评论轮询与回复:hybrid 走 CLI,browser 走原驱动 ──
176
+ listWorks: (...a) => (useCli() ? cliDriver.listWorks(...a) : browserDriver.listWorks(...a)),
177
+ openWork: (...a) => (useCli() ? cliDriver.openWork(...a) : browserDriver.openWork(...a)),
178
+ listCommentsApi: (...a) => (useCli() ? cliDriver.listCommentsApi(...a) : browserDriver.listCommentsApi?.(...a)),
179
+ listComments: (...a) => (useCli() ? cliDriver.listComments(...a) : browserDriver.listComments(...a)),
180
+ listCommentReplies: (...a) => (useCli() ? cliDriver.listCommentReplies(...a) : browserDriver.listCommentReplies?.(...a)),
181
+ replyApi: (payload, opts) => {
182
+ if (!useCli()) return browserDriver.replyApi(payload, opts);
183
+ // 带图评论:CLI 不支持传图,若浏览器在线则走浏览器接口,否则退回纯文字走 CLI
184
+ if (Array.isArray(payload?.images) && payload.images.length > 0 && canBrowser() && typeof browserDriver.replyApi === 'function') {
185
+ return browserDriver.replyApi(payload, opts);
186
+ }
187
+ return cliDriver.replyApi(payload, opts);
188
+ },
189
+ reply: (...a) => (useCli() ? cliDriver.reply(...a) : browserDriver.reply(...a))
190
+ };
191
+ }
@@ -640,6 +640,20 @@ export class DouyinSocial extends SocialBase {
640
640
  return this.host.running && this.host.loggedIn === true && Date.now() >= this.blockedUntil;
641
641
  }
642
642
 
643
+ get videoReady() {
644
+ if (this.driver?.videoNeedsBrowserLock === false) return Date.now() >= this.blockedUntil;
645
+ return this.ready;
646
+ }
647
+
648
+ get commentsReady() {
649
+ if (this.driver?.commentsNeedBrowserLock === false) return Date.now() >= this.blockedUntil;
650
+ return this.ready;
651
+ }
652
+
653
+ isReadyFor(kind = 'post') {
654
+ return kind === 'video' ? this.videoReady : this.ready;
655
+ }
656
+
643
657
  notReadyText() {
644
658
  if (Date.now() < this.blockedUntil) return '抖音刚要过验证,过几个小时再试(或者先去浏览器里验证一下)';
645
659
  return this.host.running ? '抖音还没登录' : '抖音浏览器没在运行';
@@ -691,7 +705,7 @@ export class DouyinSocial extends SocialBase {
691
705
  // 作品表用「note / video」这套说法(图文 / 视频),social.js 那边叫「post / video」——这里换一下。
692
706
  beginPost(text, date, kind = 'note') { return this.postJobs.begin(text, date, kind === 'video' ? 'video' : 'note'); }
693
707
  confirmPost(id) { this.postJobs.confirm(id); }
694
- failPost(id, error) { this.postJobs.fail(id, error); }
708
+ failPost(id, error) { this.postJobs.fail(id, error, { notAttempted: error?.notAttempted === true }); }
695
709
  async resolvePost(id, outcome) {
696
710
  const pending = this.postJobs?.pending();
697
711
  if (!pending || pending.status !== 'unknown' || pending.id !== Number(id)) return { ok: false, error: '没有这条待核实作品' };
@@ -812,8 +826,17 @@ export class DouyinSocial extends SocialBase {
812
826
  // 额度查在生成之前:超了直接抛人话,一次钱都不花(force 也照查,防手动连点刷钱)。
813
827
  const quotaErr = this.videoQuotaError(parts.dateStr);
814
828
  if (quotaErr) throw new Error(quotaErr);
815
- // 先检查创作者中心登录 cookie,避免未登录时白白调付费视频生成。
816
- if (typeof this.host?.browser?.cookies === 'function') {
829
+ // 先检查视频投稿登录态(CLI 驱动查 auth status,浏览器驱动查创作者中心 cookie),避免未登录时白白调付费视频生成。
830
+ let needCookieCheck = true;
831
+ if (typeof this.driver?.checkVideoAuth === 'function') {
832
+ const auth = await this.driver.checkVideoAuth();
833
+ if (!auth?.ok) {
834
+ this.notify('douyin.creator', auth?.error ?? '抖音 CLI 未登录或缺少投稿权限,请先扫码授权');
835
+ throw new Error(`${auth?.error ?? '抖音 CLI 未登录'},已取消生成视频,没有扣额度`);
836
+ }
837
+ needCookieCheck = auth.fallbackCookieCheck === true;
838
+ }
839
+ if (needCookieCheck && typeof this.host?.browser?.cookies === 'function') {
817
840
  const ck = await this.host.browser.cookies(['https://creator.douyin.com']).catch(() => null);
818
841
  if (Array.isArray(ck)) {
819
842
  const hasSession = ck.some((x) => x?.name === 'sessionid' || x?.name === 'sessionid_ss' || x?.name === 'sid_tt' || x?.name === 'sid_guard');
@@ -838,18 +861,13 @@ export class DouyinSocial extends SocialBase {
838
861
  let r = null;
839
862
  let song = '';
840
863
  try {
841
- // 浏览器锁的时长从转码预算**推导**,不写死常量:
842
- // exclusive 超时只把错误给调用方、锁要等 fn 真 settle 才放(见 lib/channels/douyin.js),
843
- // 给小了会出现「报了超时但页面还占着」⇒ 后面所有页面操作排队。
844
- // 转码预算 + VIDEO_LOCK_MARGIN_MS 余量(探活 / 导航 / 填表 / 发布确认)。
845
- r = await this.host.exclusive('发抖音视频', async () => {
864
+ const videoNeedsLock = this.driver?.videoNeedsBrowserLock !== false;
865
+ const runVideoPublish = async () => {
846
866
  const pre = await this.driver.prepareVideo({ title: noteTitle(text), text, file: out.file });
847
867
  if (!pre?.ok) return pre;
848
868
  try {
849
- // OpenMotion 本地渲染或无声视频:如果创作者中心编辑页有「选择音乐」,顺手从推荐里配一首 BGM;
850
- // 视频已花钱/耗时生成,页面没给选音乐入口或没挑出来时退回原声发布,不让整条视频作废。
851
869
  let allowDuplicate = false;
852
- if (cfg.provider === 'openmotion' && typeof this.driver.listRecommendedMusic === 'function') {
870
+ if (videoNeedsLock && cfg.provider === 'openmotion' && typeof this.driver.listRecommendedMusic === 'function') {
853
871
  const list = await this.driver.listRecommendedMusic().catch(() => null);
854
872
  if (list?.ok && Array.isArray(list.songs) && list.songs.length) {
855
873
  const choice = await this.chooseMusic(text, list.songs, list.counts, 'video').catch(() => ({ song: '', duplicate: false }));
@@ -864,20 +882,33 @@ export class DouyinSocial extends SocialBase {
864
882
  ...(song ? { music: song, allowDuplicate } : {}),
865
883
  beforeSubmit: () => this.postJobs.submitting(jobId)
866
884
  });
867
- await this.attachWorkId(published);
885
+ if (videoNeedsLock) await this.attachWorkId(published);
868
886
  return published;
869
887
  } finally {
870
- try { await this.driver.closeMusicPanel?.(); } catch { /* 关不掉就算了 */ }
888
+ if (videoNeedsLock) {
889
+ try { await this.driver.closeMusicPanel?.(); } catch { /* 关不掉就算了 */ }
890
+ }
871
891
  }
872
- }, { maxMs: PAGE_TIMING.transcodeBudgetMs + VIDEO_LOCK_MARGIN_MS });
892
+ };
893
+ r = videoNeedsLock
894
+ ? await this.host.exclusive('发抖音视频', runVideoPublish, { maxMs: PAGE_TIMING.transcodeBudgetMs + VIDEO_LOCK_MARGIN_MS })
895
+ : await runVideoPublish();
873
896
  } finally {
874
897
  // 发完或发布失败都清一下旧的 mp4 / 过期 .part:视频单条百 MB,失败路径也不能在盘上无限堆。
875
898
  // 删不掉不影响这次发布的结果(pruneVideos 内部吞异常,这里再兜一层)。
876
899
  try { this.videoPrune(this.videoDir); } catch { /* 清理失败不影响发布 */ }
877
900
  }
878
901
  if (r?.code === 'NEEDS_VERIFY') this.blocked('发作品');
879
- if (r?.code === 'NOT_LOGGED_IN') this.notify('douyin.creator', '想在抖音发视频,但创作者中心没登录:在抖音浏览器里打开 creator.douyin.com 登录一次就好');
880
- if (!r?.ok) throw new Error(r?.error ?? '没发出去');
902
+ if (r?.code === 'NOT_LOGGED_IN') {
903
+ this.notify('douyin.creator', this.driver?.cliActive
904
+ ? '想在抖音发视频,但 douyin-open-cli 登录已失效,请重新扫码授权'
905
+ : '想在抖音发视频,但创作者中心没登录:在抖音浏览器里打开 creator.douyin.com 登录一次就好');
906
+ }
907
+ if (!r?.ok) {
908
+ const err = new Error(r?.error ?? '没发出去');
909
+ if (r?.writeState === WRITE_NOT_ATTEMPTED) err.notAttempted = true;
910
+ throw err;
911
+ }
881
912
  this.verifyCleared(); // 这次没被拦:验证计数清零
882
913
  this.note('post', { title: this.label, reason: song ? `发了一条视频(已配乐《${song}》)` : '发了一条视频' });
883
914
  this.notify('douyin.creator', null);
@@ -904,7 +935,9 @@ export class DouyinSocial extends SocialBase {
904
935
  /** 看最近几个作品的评论区,挨个决定回不回。 */
905
936
  async pollComments() {
906
937
  const c = this.cfg();
907
- if (!c.comments.enabled || this.polling || !this.ready) return { ok: false, replied: 0, skipped: 0, error: c.comments.enabled ? this.notReadyText() : '回评论关着' };
938
+ const commentsNeedLock = this.driver?.commentsNeedBrowserLock !== false;
939
+ const isReady = commentsNeedLock ? this.ready : this.commentsReady;
940
+ if (!c.comments.enabled || this.polling || !isReady) return { ok: false, replied: 0, skipped: 0, error: c.comments.enabled ? this.notReadyText() : '回评论关着' };
908
941
  if (this.commentInBackoff()) return { ok: true, replied: 0, skipped: 0, backoff: true };
909
942
  this.polling = true;
910
943
  let replied = 0;
@@ -912,7 +945,9 @@ export class DouyinSocial extends SocialBase {
912
945
  const seeded = getKv(this.db, 'douyin.comments.seeded', false) === true;
913
946
  const selfUid = selfUidFromKv(getKv(this.db, 'douyin.selfUid', ''));
914
947
  try {
915
- const works = await this.host.exclusive('看自己的作品', () => this.driver.listWorks(3), { maxMs: 60_000 });
948
+ const works = commentsNeedLock
949
+ ? await this.host.exclusive('看自己的作品', () => this.driver.listWorks(3), { maxMs: 60_000 })
950
+ : await this.driver.listWorks(3);
916
951
  this.lastPollAt = Date.now();
917
952
  outer: for (const w of works) {
918
953
  // 从本地 social_post 补回完整文案,避免作品列表标题被截断。
@@ -935,13 +970,15 @@ export class DouyinSocial extends SocialBase {
935
970
  const codes = await this.driver.emojiCodes().catch(() => []);
936
971
  if (codes.length) this.emojiHint = codes.slice(0, 60).join(' ');
937
972
  }
938
- const comments = await this.host.exclusive('看作品评论', async () => {
939
- const o = await this.driver.openWork(w);
940
- if (!o.ok) return [];
973
+ const fetchComments = async () => {
974
+ if (commentsNeedLock) {
975
+ const o = await this.driver.openWork(w);
976
+ if (!o.ok) return [];
977
+ }
941
978
  const viaApi = typeof this.driver.listCommentsApi === 'function'
942
979
  ? await this.driver.listCommentsApi(w.id).catch(() => [])
943
980
  : [];
944
- const dom = await this.driver.listComments();
981
+ const dom = commentsNeedLock ? await this.driver.listComments() : [];
945
982
  const merged = [];
946
983
  const seenCids = new Set();
947
984
  const domAuthorKeys = new Set(dom.filter((d) => d?.isAuthor).map((d) => `${d.author}|${d.content}`));
@@ -975,7 +1012,10 @@ export class DouyinSocial extends SocialBase {
975
1012
  for (const d of dom) pushItem(d);
976
1013
  }
977
1014
  return merged;
978
- }, { maxMs: 90_000 });
1015
+ };
1016
+ const comments = commentsNeedLock
1017
+ ? await this.host.exclusive('看作品评论', fetchComments, { maxMs: 90_000 })
1018
+ : await fetchComments();
979
1019
  const STALE_MS = 24 * HOUR_MS;
980
1020
  for (const cm of comments) {
981
1021
  if (!cm.author || (!cm.content && !cm.hasImage)) continue;
@@ -1041,8 +1081,7 @@ export class DouyinSocial extends SocialBase {
1041
1081
  };
1042
1082
  let r;
1043
1083
  try {
1044
- r = await this.host.exclusive('回抖音评论', async () => {
1045
- // 有 cid 就走接口(稳、不依赖页面结构);没有(DOM 版列表)才走点击
1084
+ const runReply = async () => {
1046
1085
  if (cm.cid) {
1047
1086
  const x = await this.driver.replyApi({
1048
1087
  awemeId: w.id, cid: cm.rootCid || cm.cid,
@@ -1050,7 +1089,6 @@ export class DouyinSocial extends SocialBase {
1050
1089
  text, images: withImg.images,
1051
1090
  }, { onBeforeWrite: markSent });
1052
1091
  if (x?.ok) return x;
1053
- // ⚠️ 结果不明 = 可能已经发出去了 —— 再退回 DOM 点一次就是重复评论,比不回严重得多
1054
1092
  if (x?.writeState === WRITE_ATTEMPTED_UNKNOWN) {
1055
1093
  this.log('warn', `[fish-soul] 抖音评论接口结果不明,不再重复发:${x?.error ?? ''}`);
1056
1094
  return {
@@ -1059,15 +1097,19 @@ export class DouyinSocial extends SocialBase {
1059
1097
  error: `接口结果不明,可能已经发出去了:${x?.error ?? ''}`.slice(0, 120),
1060
1098
  };
1061
1099
  }
1062
- // 接口失败退回点击(老路),但**不重试接口** —— 重试就是重复发
1100
+ if (!commentsNeedLock) return x;
1063
1101
  this.log('warn', `[fish-soul] 抖音评论接口失败,退回点击:${x?.error ?? ''}`);
1064
1102
  }
1065
- // ⚠️ DOM 路径保守标记:进写路径就算「可能已经发出去了」(见上)
1103
+ if (!commentsNeedLock) return { ok: false, code: 'NO_CID', error: 'CLI 模式缺少评论 ID' };
1066
1104
  markSent();
1067
1105
  let x = await this.driver.reply(cm, text);
1068
- if (x?.code === 'NOT_FOUND' && (await this.driver.openWork(w)).ok) x = await this.driver.reply(cm, text); // 页面被别的事换掉了:重开一次
1106
+ if (x?.code === 'NOT_FOUND' && (await this.driver.openWork(w)).ok) x = await this.driver.reply(cm, text);
1069
1107
  return x;
1070
- }, { maxMs: 90_000 });
1108
+ };
1109
+ const replyNeedsLock = commentsNeedLock || (withImg.images.length > 0 && this.driver?.replyNeedsBrowserLock?.(withImg.images) === true);
1110
+ r = replyNeedsLock
1111
+ ? await this.host.exclusive('回抖音评论', runReply, { maxMs: 90_000 })
1112
+ : await runReply();
1071
1113
  } catch (error) {
1072
1114
  // 外层放弃:回调后面再走到写出去那一刻,就地补记 failed(见 writeAbandoned)
1073
1115
  writeAbandoned = true;
package/lib/index.js CHANGED
@@ -42,7 +42,9 @@ import { BiliClient, BiliChannel } from './channels/bilibili.js';
42
42
  import { BiliBrowser } from './browse.js';
43
43
  import { videoFrames, douyinFrames } from './video-frames.js';
44
44
  import { BiliSocial } from './social.js';
45
- import { DouyinSocial } from './douyin-social.js';
45
+ import { DouyinSocial, douyinSocialDriver } from './douyin-social.js';
46
+ import { DouyinCli } from './douyin-cli.js';
47
+ import { douyinSocialCliDriver, hybridDouyinSocialDriver } from './douyin-social-cli.js';
46
48
  import { DouyinHost, DouyinChannel } from './channels/douyin.js';
47
49
  import { DouyinBrowser } from './douyin-browse.js';
48
50
  import { DouyinHttp } from './douyin-http.js';
@@ -303,20 +305,28 @@ async function startup(ctx, config, { log, gate }) {
303
305
  http: douyinHttp, // 纯 HTTP 客户端:快路径用它的 cookie jar(拿不到就退浏览器)
304
306
  driver: hook.driver?.(douyinHost), pollRangeMs: hook.pollRangeMs, typingMs: hook.typingMs, firstPollMs: hook.firstPollMs
305
307
  });
308
+ const douyinCli = new DouyinCli({ getConfig: () => douyinCfg().cli ?? {}, log });
306
309
  const douyinBrowser = new DouyinBrowser({
307
310
  db, clock, host: douyinHost, getConfig: douyinCfg, callLlm: llmRouter.bound('browse'), worker, log,
308
311
  dwellMs: hook.dwellMs, settleMs: hook.settleMs, readDetail: hook.readDetail, fetchImpl: hook.fetch,
309
312
  // 纯 HTTP 客户端(刷视频 / 读评论走这条路;cookie 从浏览器 CDP 抓一次落盘,之后浏览器可以关)
310
313
  http: douyinHttp,
314
+ cli: douyinCli,
311
315
  // 抽帧看画面(douyin.browse.frames 开才用):play_addr 直链 → ffmpeg 九宫格。
312
316
  // 超时 90 秒(抖音 CDN 会挂);一条失败不影响她看完这条,照旧只看文字。
313
317
  frames: (v) => douyinFrames(v.urls, { id: v.id, durationMs: v.durationMs, signal: AbortSignal.timeout(90_000) }),
314
318
  share: (x) => life.queueShare(x), shareFallback: (x) => life.queueShareFallback(x), note: (k, x) => gateway?.note(k, x),
315
319
  persona: () => ({ name: persona.name, brief: personaBrief() })
316
320
  });
317
- // 抖音自己发图文 / 回评论(默认都关;走专用浏览器,尽力而为)
321
+ // 抖音自己发图文 / 发视频 / 回评论(hybrid 模式把发视频与评论切到 douyin-open-cli,图文保留浏览器)
318
322
  const douyinSocial = new DouyinSocial({
319
323
  db, clock, host: douyinHost, getConfig: douyinCfg, callLlm: llmRouter.bound('social'), worker, log, notify: notifyMaster, rewriteLlm: llmRouter.bound('rewrite'), behaviorCfg: () => behaviorConfig(currentConfig.behavior),
324
+ driver: hybridDouyinSocialDriver({
325
+ browserDriver: douyinSocialDriver(douyinHost),
326
+ cliDriver: douyinSocialCliDriver(douyinCli, { log }),
327
+ getMode: () => douyinCfg().cli?.socialBackend ?? 'browser',
328
+ browserReady: () => douyinHost.running && douyinHost.loggedIn === true
329
+ }),
320
330
  // 图片评论:发她自己 _stickers 库里的表情包(模型挑),上传走已验证的 ImageX 链路。
321
331
  // ⚠️ stickers 在下面(799 行附近)才 new —— 这里用 getter 惰性拿,别提前引用。
322
332
  stickers: () => stickersBox, embedder, workspacePath: () => gateway?.workspacePath() ?? '', canvasConvert: (bytes) => douyinHost.canvasConvert(bytes),
@@ -1219,7 +1229,7 @@ async function startup(ctx, config, { log, gate }) {
1219
1229
  registerRoutes(ctx, {
1220
1230
  gate,
1221
1231
  ctx, // /update/ 那组路由要靠它找宿主的 plugin-manager 服务(一键更新)
1222
- db, clock, embedder, embeddingCfg, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial, douyinSocial,
1232
+ db, clock, embedder, embeddingCfg, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial, douyinSocial, douyinCli,
1223
1233
  douyin, douyinHost, douyinBrowser, backup, historyImporter, updater, worldBooks,
1224
1234
  llmRouter, voice, stickers, slang, persona, reloadPersona, webConfig, hasWebTools, webUsedToday, hostWebAvailable, hostWebState, runWebSearch,
1225
1235
  journal, digester, diary, weekly, storage, chatArchive, diag,
@@ -4,6 +4,7 @@
4
4
  * ⚠️ 下面 handleDouyinRoute 里的 sameOrigin 总闸必须留在**前 80 行**内(check-route-guard.mjs 认这个窗口)。
5
5
  */
6
6
  import { existsSync, statSync } from 'node:fs';
7
+ import { isAbsolute } from 'node:path';
7
8
  import { sharpReady } from './imageconv.js';
8
9
  import { videoGenConfig } from './video-gen.js';
9
10
  import { clampReplyWindow } from './gateway-util.js';
@@ -62,6 +63,7 @@ export function douyinState({ getConfig, life, clock, douyin, douyinHost, douyin
62
63
  post: { enabled: d.post?.enabled === true, perDay: d.post?.perDay ?? 1 },
63
64
  // 视频块(面板在 PR3,但这块得能回显 —— 存进去读不回来 = 死输入框)。
64
65
  video: videoEcho(d),
66
+ cli: cliEcho(d),
65
67
  comments: { enabled: d.comments?.enabled === true, perHour: d.comments?.perHour ?? 4, emoji: d.comments?.emoji === true },
66
68
  social: douyinSocial?.status() ?? null,
67
69
  sharp: sharpReady()
@@ -72,7 +74,7 @@ const names = (list) => (Array.isArray(list) ? list : []).map((x) => String(x).t
72
74
 
73
75
  /** 处理 /channels/douyin-config 和 /douyin/*;不是抖音的路由返回 false。 */
74
76
  export async function handleDouyinRoute({ method, path, req, send, readBody, sameOrigin, deps }) {
75
- const { getConfig, saveConfig, log, douyin, douyinHost, douyinBrowser, douyinSocial, gateway } = deps;
77
+ const { getConfig, saveConfig, log, douyin, douyinHost, douyinBrowser, douyinSocial, douyinCli, gateway } = deps;
76
78
  if (path !== '/channels/douyin-config' && !path.startsWith('/douyin/')) return false;
77
79
  if (method !== 'POST') { send(405, { ok: false, error: 'method not allowed' }); return true; }
78
80
  if (!sameOrigin(req)) { send(403, { ok: false, error: 'forbidden' }); return true; }
@@ -115,6 +117,16 @@ export async function handleDouyinRoute({ method, path, req, send, readBody, sam
115
117
  const cbr = cur.browse ?? {};
116
118
  const bv = body.video ?? {};
117
119
  const cv = cur.video ?? {};
120
+ const cliBinary = body.cli?.binaryPath === undefined ? String(cur.cli?.binaryPath ?? 'douyin-open-cli') : (String(body.cli.binaryPath).trim() || 'douyin-open-cli');
121
+ if (cliBinary !== 'douyin-open-cli') {
122
+ let okBin = false;
123
+ try { okBin = existsSync(cliBinary) && statSync(cliBinary).isFile(); } catch { okBin = false; }
124
+ if (!okBin) { send(200, { ok: false, error: '指定的 douyin-open-cli 路径不存在或不是文件' }); return true; }
125
+ }
126
+ const cliAuthDir = body.cli?.authDir === undefined ? String(cur.cli?.authDir ?? '') : String(body.cli.authDir).trim();
127
+ if (cliAuthDir !== '' && !isAbsolute(cliAuthDir)) {
128
+ send(200, { ok: false, error: 'CLI 凭证目录必须填写绝对路径' }); return true;
129
+ }
118
130
  const next = {
119
131
  enabled: body.enabled === undefined ? cur.enabled === true : body.enabled === true,
120
132
  autoReply: body.autoReply === undefined ? cur.autoReply === true : body.autoReply === true,
@@ -168,6 +180,14 @@ export async function handleDouyinRoute({ method, path, req, send, readBody, sam
168
180
  enabled: body.comments?.enabled === undefined ? cur.comments?.enabled === true : body.comments.enabled === true,
169
181
  perHour: clamp(body.comments?.perHour, cur.comments?.perHour ?? 4, 0, 30),
170
182
  emoji: body.comments?.emoji === undefined ? cur.comments?.emoji === true : body.comments.emoji === true
183
+ },
184
+ cli: {
185
+ socialBackend: body.cli?.socialBackend === undefined
186
+ ? (cur.cli?.socialBackend === 'hybrid' ? 'hybrid' : 'browser')
187
+ : (body.cli.socialBackend === 'hybrid' ? 'hybrid' : 'browser'),
188
+ binaryPath: cliBinary,
189
+ authDir: cliAuthDir,
190
+ browseText: body.cli?.browseText === undefined ? cur.cli?.browseText === true : body.cli.browseText === true
171
191
  }
172
192
  };
173
193
  const wasOn = cur.enabled === true;
@@ -298,7 +318,7 @@ export async function handleDouyinRoute({ method, path, req, send, readBody, sam
298
318
  const blocked = douyinSocial.postBlockReason?.();
299
319
  if (blocked) { send(200, { ok: false, error: blocked }); return true; }
300
320
  if (douyinSocial.posting) { send(200, { ok: false, error: '正在发,稍等' }); return true; }
301
- if (!douyinSocial.ready) { send(200, { ok: false, error: douyinSocial.notReadyText() }); return true; }
321
+ if (!(douyinSocial.videoReady ?? douyinSocial.ready)) { send(200, { ok: false, error: douyinSocial.notReadyText() }); return true; }
302
322
  // ⚠️ force 只跳「次数和间隔」,跳不掉每天的条数上限 —— 视频生成是花钱的,
303
323
  // 手动点也得受每天上限保护(见 douyin-social.js 的 publishVideoWork)。
304
324
  const quotaErr = douyinSocial.videoQuotaError?.();
@@ -322,6 +342,22 @@ export async function handleDouyinRoute({ method, path, req, send, readBody, sam
322
342
  send(200, r.ok ? { ok: true, replied: r.replied, skipped: r.skipped } : { ok: false, error: r.error ?? '没看成' });
323
343
  return true;
324
344
  }
345
+ // ── douyin-open-cli 登录与状态路由 ──
346
+ if (path === '/douyin/cli/status') {
347
+ if (!douyinCli) { send(200, { ok: false, error: '抖音 CLI 模块未加载' }); return true; }
348
+ send(200, await douyinCli.authStatus());
349
+ return true;
350
+ }
351
+ if (path === '/douyin/cli/login/begin') {
352
+ if (!douyinCli) { send(200, { ok: false, error: '抖音 CLI 模块未加载' }); return true; }
353
+ send(200, await douyinCli.authLoginBegin({ force: body.force === true }));
354
+ return true;
355
+ }
356
+ if (path === '/douyin/cli/login/complete') {
357
+ if (!douyinCli) { send(200, { ok: false, error: '抖音 CLI 模块未加载' }); return true; }
358
+ send(200, await douyinCli.authLoginComplete());
359
+ return true;
360
+ }
325
361
  send(404, { ok: false, error: 'not found' });
326
362
  return true;
327
363
  }
@@ -351,3 +387,14 @@ function videoEcho(d) {
351
387
  apiKeyMasked: maskKey(v.apiKey)
352
388
  };
353
389
  }
390
+
391
+ /** 抖音开放 CLI 配置回显(放在文件末尾,避免挤出前 80 行 sameOrigin 检查窗口)。 */
392
+ function cliEcho(d) {
393
+ const c = d.cli ?? {};
394
+ return {
395
+ socialBackend: c.socialBackend === 'hybrid' ? 'hybrid' : 'browser',
396
+ binaryPath: String(c.binaryPath ?? '').trim() || 'douyin-open-cli',
397
+ authDir: String(c.authDir ?? '').trim(),
398
+ browseText: c.browseText === true
399
+ };
400
+ }
package/lib/social.js CHANGED
@@ -212,9 +212,11 @@ export class SocialBase {
212
212
  * 两种类型**不共用**随机摊派,但共用「同一时刻只发一条」的锁
213
213
  * (posting + 30 分钟真实间隔):一条正在发时另一种不抢。
214
214
  */
215
+ isReadyFor(_kind = 'post') { return this.ready; }
216
+
215
217
  maybePost({ parts, slot, mood, activeHours = [8, 24], kind = 'post' }) {
216
218
  const c = kind === 'video' ? this.cfg().video : this.cfg().post;
217
- if (!c.enabled || c.perDay === 0 || this.posting || !this.ready || this.postBlockReason?.()) return false;
219
+ if (!c.enabled || c.perDay === 0 || this.posting || !this.isReadyFor(kind) || this.postBlockReason?.()) return false;
218
220
  const [start, end] = activeHours;
219
221
  if (parts.hour < start || parts.hour >= end) return false;
220
222
  if (slot?.availability === 'sleeping') return false;
@@ -360,7 +362,7 @@ export class SocialBase {
360
362
  const blocked = this.postBlockReason?.(kind);
361
363
  if (blocked) return { ok: false, error: blocked };
362
364
  if (this.posting) return { ok: false, error: '正在发,稍等' };
363
- if (!this.ready) return { ok: false, error: this.notReadyText() };
365
+ if (!this.isReadyFor(kind)) return { ok: false, error: this.notReadyText() };
364
366
  this.posting = true;
365
367
  this.postingKind = kind;
366
368
  const p = parts ?? this.clock.getRoleDateParts();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-soul",
3
- "version": "0.19.30",
3
+ "version": "0.19.31",
4
4
  "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "scripts": {
67
- "test": "node test/check-test-chain.mjs && node test/config-shape-contract.mjs && node test/affected-suites-clean.mjs && node test/new-export-gate-rule.mjs && node test/check-commit-author.mjs && node test/check-docs-version-refs.mjs && node test/affected-suites-test.mjs && node test/check-commit-author-rule.mjs && node test/check-commit-author-wire.mjs && node test/check-docs-version-refs-rule.mjs && node test/check-docs-version-refs-wire.mjs && node test/check-release-version.mjs && node test/wire-helper.mjs && node test/marker-audit.mjs && node test/douyin-send.mjs && node test/douyin-mechanism.mjs && node test/douyin-route.mjs && node test/douyin-adapter.mjs && node test/douyin-contract.mjs && node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-push-poll-dedupe.mjs && node test/douyin-share-card-dedupe.mjs && node test/douyin-share-card-dom.mjs && node test/douyin-inline-share.mjs && node test/douyin-short-link.mjs && node test/douyin-inline-ledger.mjs && node test/douyin-group-chat.mjs && node test/douyin-group-read.mjs && node test/douyin-group-reply.mjs && node test/session-overflow-recycle.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-meta-lines.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-live-fails.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-note-upload-poll.mjs && node test/douyin-post-jobs.mjs && node test/douyin-video-post.mjs && node test/douyin-video-trigger.mjs && node test/douyin-video-driver.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/prompts.mjs && node test/prompts-route.mjs && node test/diary-topics-217.mjs && node test/smoke.mjs && node test/life-context-interaction.mjs && node test/life-pet-token.mjs && node test/desktop-pet-token-panel.mjs && node test/life-clock-refresh.mjs && node test/browser-launch-early-exit.mjs && node test/douyin-browser.mjs && node test/douyin-crash-restore.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/douyin-ax-button.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/slang-global.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/retrieval-tier-weights.mjs && node test/retrieval-tier-weights-route.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/llm-roomy-budget.mjs && node test/llm-failure-backoff.mjs && node test/llm-budget-and-social-backoff.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/dsh-desktop-as-master.mjs && node test/desktop-as-master-switch.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/diag-douyin-running.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/repeat-guard-cross-turn.mjs && node test/voice-paragraph-split.mjs && node test/voice-paragraph-split-wire.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/douyin-panel-width-threshold.mjs && node test/douyin-emoji-panel-close.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-sender-id.mjs && node test/data-dir.mjs && node test/data-dir-panel.mjs && node test/dsh-home-guard.mjs && node test/relay-config-route.mjs && node test/share-fallback.mjs && node test/share-quota-refund.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/outbound-quote-and-images.mjs && node test/sticker-bracket-fallback.mjs && node test/dream-transcript-scope.mjs && node test/memory-date-context.mjs && node test/memory-time-dedupe.mjs && node test/context-source-platform.mjs && node test/memory-source-label.mjs && node test/issue-239-maxtokens-wire.mjs && node test/issue-239-maxtokens.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-comment-link.mjs && node test/bili-comment-visibility.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/vision-model.mjs && node test/image-inbound-fail.mjs && node test/group-backlog-images.mjs && node test/group-master-tag.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/chat-archive-fts.mjs && node test/chat-search-tool.mjs && node test/memory-invalidate-kind.mjs && node test/dream-merge-duplicates.mjs && node test/mood-guard.mjs && node test/time-awareness.mjs && node test/tts-strip-emoji.mjs && node test/session-reset-route.mjs && node test/check-secrets.mjs && node test/check-secrets-nickname.mjs && node test/check-docs-freshness.mjs && node test/check-package-json-format.mjs && node test/wire-limits.mjs && node test/check-chromium-suites.mjs && node test/check-no-stash-scripts.mjs && node test/douyin-video-wire.mjs && node test/douyin-self-uid.mjs && node test/douyin-group-cursor.mjs && node test/douyin-dom-text.mjs && node test/video-gen.mjs && node test/scheduled-tasks.mjs && node test/scheduled-tasks-ui.mjs && node test/douyin-wave12-fixes.mjs && node test/prefetch-vec-await.mjs && node test/wave2-token-optimizations.mjs && node test/wave3-memory-retrieval.mjs && node test/rc5-token-inflation.mjs && node test/pending-surfaced-closure.mjs && node test/memory-digest-retry-239.mjs && node test/issue-244-paragraph-split.mjs && node test/issue-244-cleanout-e2e.mjs && node test/issue-269-qq-split-budget.mjs && node test/voice-mention-guard.mjs && node test/issue-247-media-url.mjs && node test/check-fork-pr-gate.mjs && node test/check-pr-hygiene.mjs && node test/check-import-cycles.mjs && node test/check-file-size-budget.mjs && node test/check-file-size-budget-rule.mjs && node test/check-silent-catch.mjs && node test/check-silent-catch-rule.mjs && node test/douyin-cookie-refresh.mjs && node test/douyin-back-to-list.mjs && node test/douyin-fastpath.mjs && node test/douyin-post-id-backfill.mjs && node test/douyin-canary-panel.mjs && node test/douyin-note-text.mjs && node test/bili-playback.mjs && node test/prompts-diary.mjs && node test/interject-interest.mjs && node test/transcript-master-only.mjs && node test/usage-visualization.mjs && node test/douyin-media-id-dedupe.mjs",
67
+ "test": "node test/check-test-chain.mjs && node test/config-shape-contract.mjs && node test/affected-suites-clean.mjs && node test/new-export-gate-rule.mjs && node test/check-commit-author.mjs && node test/check-docs-version-refs.mjs && node test/affected-suites-test.mjs && node test/check-commit-author-rule.mjs && node test/check-commit-author-wire.mjs && node test/check-docs-version-refs-rule.mjs && node test/check-docs-version-refs-wire.mjs && node test/check-release-version.mjs && node test/wire-helper.mjs && node test/marker-audit.mjs && node test/douyin-send.mjs && node test/douyin-mechanism.mjs && node test/douyin-route.mjs && node test/douyin-adapter.mjs && node test/douyin-contract.mjs && node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-push-poll-dedupe.mjs && node test/douyin-share-card-dedupe.mjs && node test/douyin-share-card-dom.mjs && node test/douyin-inline-share.mjs && node test/douyin-short-link.mjs && node test/douyin-inline-ledger.mjs && node test/douyin-group-chat.mjs && node test/douyin-group-read.mjs && node test/douyin-group-reply.mjs && node test/session-overflow-recycle.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-meta-lines.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-live-fails.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-note-upload-poll.mjs && node test/douyin-post-jobs.mjs && node test/douyin-video-post.mjs && node test/douyin-video-trigger.mjs && node test/douyin-video-driver.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/prompts.mjs && node test/prompts-route.mjs && node test/diary-topics-217.mjs && node test/smoke.mjs && node test/life-context-interaction.mjs && node test/life-pet-token.mjs && node test/desktop-pet-token-panel.mjs && node test/life-clock-refresh.mjs && node test/browser-launch-early-exit.mjs && node test/douyin-browser.mjs && node test/douyin-crash-restore.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/douyin-ax-button.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/slang-global.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/retrieval-tier-weights.mjs && node test/retrieval-tier-weights-route.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/llm-roomy-budget.mjs && node test/llm-failure-backoff.mjs && node test/llm-budget-and-social-backoff.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/dsh-desktop-as-master.mjs && node test/desktop-as-master-switch.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/diag-douyin-running.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/repeat-guard-cross-turn.mjs && node test/voice-paragraph-split.mjs && node test/voice-paragraph-split-wire.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/douyin-panel-width-threshold.mjs && node test/douyin-emoji-panel-close.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-sender-id.mjs && node test/data-dir.mjs && node test/data-dir-panel.mjs && node test/dsh-home-guard.mjs && node test/relay-config-route.mjs && node test/share-fallback.mjs && node test/share-quota-refund.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/outbound-quote-and-images.mjs && node test/sticker-bracket-fallback.mjs && node test/dream-transcript-scope.mjs && node test/memory-date-context.mjs && node test/memory-time-dedupe.mjs && node test/context-source-platform.mjs && node test/memory-source-label.mjs && node test/issue-239-maxtokens-wire.mjs && node test/issue-239-maxtokens.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-comment-link.mjs && node test/bili-comment-visibility.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/vision-model.mjs && node test/image-inbound-fail.mjs && node test/group-backlog-images.mjs && node test/group-master-tag.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/chat-archive-fts.mjs && node test/chat-search-tool.mjs && node test/memory-invalidate-kind.mjs && node test/dream-merge-duplicates.mjs && node test/mood-guard.mjs && node test/time-awareness.mjs && node test/tts-strip-emoji.mjs && node test/session-reset-route.mjs && node test/check-secrets.mjs && node test/check-secrets-nickname.mjs && node test/check-docs-freshness.mjs && node test/check-package-json-format.mjs && node test/wire-limits.mjs && node test/check-chromium-suites.mjs && node test/check-no-stash-scripts.mjs && node test/douyin-video-wire.mjs && node test/douyin-self-uid.mjs && node test/douyin-group-cursor.mjs && node test/douyin-dom-text.mjs && node test/video-gen.mjs && node test/scheduled-tasks.mjs && node test/scheduled-tasks-ui.mjs && node test/douyin-wave12-fixes.mjs && node test/prefetch-vec-await.mjs && node test/wave2-token-optimizations.mjs && node test/wave3-memory-retrieval.mjs && node test/rc5-token-inflation.mjs && node test/pending-surfaced-closure.mjs && node test/memory-digest-retry-239.mjs && node test/issue-244-paragraph-split.mjs && node test/issue-244-cleanout-e2e.mjs && node test/issue-269-qq-split-budget.mjs && node test/voice-mention-guard.mjs && node test/issue-247-media-url.mjs && node test/check-fork-pr-gate.mjs && node test/check-pr-hygiene.mjs && node test/check-import-cycles.mjs && node test/check-file-size-budget.mjs && node test/check-file-size-budget-rule.mjs && node test/check-silent-catch.mjs && node test/check-silent-catch-rule.mjs && node test/douyin-cookie-refresh.mjs && node test/douyin-back-to-list.mjs && node test/douyin-fastpath.mjs && node test/douyin-post-id-backfill.mjs && node test/douyin-canary-panel.mjs && node test/douyin-note-text.mjs && node test/bili-playback.mjs && node test/prompts-diary.mjs && node test/interject-interest.mjs && node test/transcript-master-only.mjs && node test/usage-visualization.mjs && node test/douyin-media-id-dedupe.mjs && node test/douyin-social-cli.mjs",
68
68
  "test:douyin": "node test/parallel.mjs 4 --only douyin",
69
69
  "test:fast": "node test/parallel.mjs 4 --skip \"douyin|browser\"",
70
70
  "typecheck": "npx --yes -p typescript tsc -p tsconfig.check.json"