dsh-fish-soul 0.18.6 → 0.18.8

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.6**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.18.8**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
package/lib/browse.js CHANGED
@@ -35,7 +35,29 @@ export function afterRound(self, label, watched, pick) {
35
35
  });
36
36
  } catch { /* 动态可缺 */ }
37
37
  const s = watched.find((w) => w.share);
38
- if (!s || typeof self.share !== 'function') return;
38
+ // 模型这轮没标 [分享]:让自走层判断要不要主动挑一条(最近几天没分享过才挑,见 #133)。
39
+ // 原来这里是直接 return ⇒ 她不标就一条都不排,主人看到的就是「刷了但从不分享」。
40
+ if (!s) {
41
+ if (typeof self.shareFallback !== 'function') return;
42
+ // ⚠️ 用户在平台面板上明确关了「刷到就分享」⇒ 兜底也不许发。
43
+ // 不看这个开关的话,兜底会把用户的显式关闭**反转**(比不修更糟)。
44
+ if (typeof self.cfg === 'function' && self.cfg()?.share === false) return;
45
+ try {
46
+ const candidates = watched.map((w) => ({ ...pick(w), impression: w.impression, skipped: w.skipped, url: w.url }));
47
+ const r = self.shareFallback({ platform: label, candidates });
48
+ if (r?.ok) {
49
+ // 用它返回的那条(挑的规则在自走层那边,自己重算可能挑到不一样的)
50
+ const one = r.chosen ?? candidates.find((c) => c.impression) ?? candidates[0];
51
+ self.note?.('share', { title: label, reason: `最近没分享,主动挑一条《${String(one?.title ?? '').slice(0, 20)}》分享给你`, text: one?.url ?? '' });
52
+ } else if (r?.error && !/最近 .* 天分享过了|没有值得分享|兜底关着|分享视频关着/.test(r.error)) {
53
+ self.note?.('browse', { title: label, reason: `想主动分享但没排上:${r.error}` });
54
+ }
55
+ } catch (error) {
56
+ self.log('warn', `[fish-soul] 兜底分享失败:${String(error instanceof Error ? error.message : error)}`);
57
+ }
58
+ return;
59
+ }
60
+ if (typeof self.share !== 'function') return;
39
61
  try {
40
62
  const r = self.share({ platform: label, ...pick(s), url: s.url, impression: s.impression });
41
63
  self.note?.(r?.ok ? 'share' : 'browse', { title: label, reason: r?.ok ? `想把《${String(pick(s).title ?? '').slice(0, 20)}》分享给你` : `想分享但没排上:${r?.error ?? '不知道为什么'}`, text: s.url });
@@ -57,8 +79,11 @@ export class BiliBrowser {
57
79
  * @param {(level: string, msg: string) => void} [deps.log]
58
80
  * @param {[number, number]} [deps.watchDelayMs] 两条视频之间"看"多久(真实毫秒)
59
81
  */
60
- constructor({ db, clock, client, getConfig, callLlm, persona, worker, log, watchDelayMs = [8000, 20000], share, note, frames }) {
82
+ constructor({ db, clock, client, getConfig, callLlm, persona, worker, log, watchDelayMs = [8000, 20000], share, shareFallback, note, frames }) {
61
83
  this.share = share ?? null; // 刷到特别想分享的:交给自走层排一条主动消息(带链接)
84
+ // #133:模型没标 [分享] 时的兜底(最近几天没分享过就主动挑一条)。
85
+ // ⚠️ 漏了这个参数整个兜底就是死代码(afterRound 里 self.shareFallback 恒 undefined)。
86
+ this.shareFallback = shareFallback ?? null;
62
87
  this.note = note ?? null; // 记一条动态
63
88
  this.db = db;
64
89
  this.clock = clock;
package/lib/client.js CHANGED
@@ -437,6 +437,7 @@ window.__ModuleLoader__.load({
437
437
  enabled: pc.enabled !== false, dailyMaxCount: pc.dailyMaxCount ?? 10,
438
438
  activeStart: pc.activeHours?.[0] ?? 8, activeEnd: pc.activeHours?.[1] ?? 24, idleTriggerHours: pc.idleTriggerHours ?? 6,
439
439
  idleRealGapMinutes: pc.idleRealGapMinutes ?? 30, scheduleEnabled: pc.scheduleEnabled !== false,
440
+ shareMaxPerDay: pc.shareMaxPerDay ?? 2, shareFallbackDays: pc.shareFallbackDays ?? 2,
440
441
  masterPrivateChannelId: targets.masterPrivateChannelId ?? "", selfGroupChannelIds: [...(targets.selfGroupChannelIds ?? [])]
441
442
  }));
442
443
  if (!data || !form) return null;
@@ -456,6 +457,9 @@ window.__ModuleLoader__.load({
456
457
  idleTriggerHours: next.idleTriggerHours,
457
458
  idleRealGapMinutes: next.idleRealGapMinutes,
458
459
  scheduleEnabled: next.scheduleEnabled,
460
+ // #133:这两个字段不进 body ⇒ 面板改了存不进去(读回又是默认值,像保存失败但没报错)
461
+ shareMaxPerDay: next.shareMaxPerDay,
462
+ shareFallbackDays: next.shareFallbackDays,
459
463
  targets: { masterCanonicalId: targets.masterCanonicalId ?? "user:master", masterPrivateChannelId: next.masterPrivateChannelId, selfGroupChannelIds: next.selfGroupChannelIds }
460
464
  });
461
465
  if (res?.ok) refresh(); else notify(res?.error ?? "保存失败");
@@ -489,6 +493,12 @@ window.__ModuleLoader__.load({
489
493
  form.enabled ? Row({ title: "空闲多久后" }, num("idleTriggerHours", "空闲多久后", 1, 48, 6), Muted("小时")) : null,
490
494
  form.enabled ? Row({ title: "刚聊完先等等" }, num("idleRealGapMinutes", "刚聊完先等等", 0, 1440, 30), Muted("分钟"), Muted("0 = 不等")) : null,
491
495
  form.enabled ? Row({ title: "自走日程" }, h(Switch, { label: "自走日程", checked: form.scheduleEnabled, onChange: (v) => save({ scheduleEnabled: v }) }), Muted("关掉就不排今天干什么")) : null,
496
+ form.enabled ? Row({ title: "分享视频", stack: true },
497
+ num("shareMaxPerDay", "分享视频每天最多", 0, 20, 2), Muted("条/天"),
498
+ Muted("她刷到特别想分享的才会发")) : null,
499
+ form.enabled ? Row({ title: "几天没分享就主动挑一条", stack: true },
500
+ num("shareFallbackDays", "几天没分享就主动挑一条", 0, 30, 2), Muted("天"),
501
+ Muted("0 = 不主动挑(只用她自己想分享的)")) : null,
492
502
  form.enabled ? Row({ title: "主人私聊" }, Input({ value: form.masterPrivateChannelId, placeholder: "private:主人 QQ", onChange: (e) => patch({ masterPrivateChannelId: e.target.value }), onBlur: () => save() })) : null,
493
503
  form.enabled ? Row({ title: "群聊", stack: true },
494
504
  ...form.selfGroupChannelIds.map((cid) => Tag(cid, undefined, { key: cid },
@@ -497,6 +507,40 @@ window.__ModuleLoader__.load({
497
507
  Button({ variant: "ghost", disabled: newGroup.trim() === "", onClick: addGroup }, "添加")) : null));
498
508
  }
499
509
 
510
+ // ── 熟人传话:白名单里的人可以托她给白名单里的另一个人带句话(默认关)──
511
+ function RelayPane({ data, refresh, notify }) {
512
+ const rc = data?.relayConfig ?? {};
513
+ const [form, setForm, patch] = useForm(data, () => ({
514
+ enabled: rc.enabled === true,
515
+ allowList: (rc.allowList ?? []).join(", "),
516
+ perDay: rc.perDay ?? 5
517
+ }));
518
+ if (!data || !form) return null;
519
+
520
+ async function save(p = {}) {
521
+ const next = { ...form, ...p };
522
+ setForm(next);
523
+ const res = await api("POST", "/relay/config", {
524
+ enabled: next.enabled === true,
525
+ allowList: split(next.allowList),
526
+ perDay: Number(next.perDay)
527
+ });
528
+ if (res?.ok) refresh(); else notify(res?.error ?? "保存失败");
529
+ }
530
+
531
+ return h(react.Fragment, null,
532
+ Group({ className: "fs-life-settings" },
533
+ Row({ title: "熟人传话", stack: true },
534
+ h(Switch, { label: "熟人传话", checked: form.enabled, onChange: (v) => save({ enabled: v }) }),
535
+ Muted("打开后,白名单里的人可以让她给对方带一句话。发出的消息会自动带「xx托我带句话」前缀 —— 收件人知道是谁说的,她不能匿名传话。")),
536
+ form.enabled ? Row({ title: "白名单", stack: true },
537
+ Area({ value: form.allowList, placeholder: "平台 uid,逗号或换行分隔:\nqq:12345678\nbili:1234567890\ndouyin:1234567890123456789", onChange: (e) => patch({ allowList: e.target.value }), onBlur: () => save() }),
538
+ Muted("填平台 uid,不是昵称 —— 昵称可以改、可以撞名。发起人和收件人都要在这里面。")) : null,
539
+ form.enabled ? Row({ title: "每人每天最多", stack: true },
540
+ Num({ min: 1, max: 50, value: form.perDay, "aria-label": "每人每天最多", onChange: (e) => patch({ perDay: e.target.value === "" ? "" : Number(e.target.value) }), onBlur: () => save({ perDay: form.perDay === "" ? 5 : form.perDay }) }),
541
+ Muted("条。到上限就拒,防止拿她当群发工具。")) : null));
542
+ }
543
+
500
544
  // ── QQ 接入(SnowLuma 直连)与会话工作区 ──
501
545
  function ChannelPane({ data, refresh, notify }) {
502
546
  const qq = data?.qq ?? {};
@@ -855,7 +899,7 @@ window.__ModuleLoader__.load({
855
899
  const TABS = [
856
900
  ["memory", "记忆", [["retrieval", "检索设置"], ["people", "人物与关系"], ["memories", "记忆内容"], ["recall-test", "检索测试"], ["weekly", "周记"], ["archives", "记忆存档"], ["backups", "导入与备份"]]],
857
901
  ["character", "角色", [["persona", "人格卡"], ["templates", "人格模板"], ["growth", "成长"], ["worldinfo", "世界书"], ["habits", "说话习惯"], ["groups", "群设定"], ["chat-models", "聊天模型"]]],
858
- ["daily", "日常", [["life", "主动开口"], ["activity", "最近动态"], ["diary", "日记"], ["stickers", "表情包"], ["slang", "学到的说法"]]],
902
+ ["daily", "日常", [["life", "主动开口"], ["relay", "熟人传话"], ["activity", "最近动态"], ["diary", "日记"], ["stickers", "表情包"], ["slang", "学到的说法"]]],
859
903
  ["channels", "平台", [["qq", "QQ"], ["bili", "B站"], ["douyin", "抖音"]]],
860
904
  ["models", "模型", [["models", "功能模型"], ["usage", "用量与价格"], ["web", "联网搜索"], ["voice", "语音"]]],
861
905
  ["system", "系统", [["interface", "界面"], ["version", "版本更新"], ["diag", "运行日志"]]]
@@ -920,6 +964,13 @@ window.__ModuleLoader__.load({
920
964
  if (r?.ok) { setData(r); notify(`已更新到 v${r.to},重启 DSH 生效`); }
921
965
  else notify(r?.error ?? "没更新成");
922
966
  }
967
+ // 开发目录(link)安装:更新 = 在那个目录里 git pull + 重启 DSH,不是 pnpm add。
968
+ // 用真实的开发目录路径,别给占位符(复制过去直接报错,等于没给命令)。
969
+ const devPath = String(data.installPath ?? "");
970
+ const devCommand = devPath === "" ? "在开发目录里 git pull,然后重启 DSH" : `git -C "${devPath}" pull && 重启 DSH`;
971
+ async function copyDev() {
972
+ try { await navigator.clipboard.writeText(devCommand); notify("已复制更新命令"); } catch { notify("复制失败,手动选中复制"); }
973
+ }
923
974
  const when = data.checkedAt ? new Date(data.checkedAt).toLocaleString("zh-CN", { hour12: false }) : "";
924
975
  const status = data.hasUpdate ? Tag(`有新版本 v${data.latest}`, "warning")
925
976
  : data.latest ? Tag("已是最新", "success")
@@ -930,11 +981,20 @@ window.__ModuleLoader__.load({
930
981
  Row({ title: status, meta: when ? `${when}${data.source ? ` · ${data.source}` : ""}` : undefined, desc: "每 12 小时自动看一次 npm / GitHub" },
931
982
  Button({ onClick: check, disabled: busy || data.checking }, busy || data.checking ? "检查中…" : "检查更新"),
932
983
  data.hasUpdate ? Button({ onClick: () => window.open(data.notesUrl, "_blank", "noopener") }, "更新说明") : null,
984
+ // ⚠️ 按钮的显隐由 **canApply**(宿主有没有插件管理服务)决定,
985
+ // 不是由 installMode 决定 —— 宿主才是唯一权威(updateBundle 自己会拒
986
+ // link 装并给出明确理由)。插件拿自己的启发式去藏按钮,
987
+ // 等于把「判据可能出错」从「多一句废话」升级成「功能直接没了」。
933
988
  data.hasUpdate && data.canApply ? Button({ variant: "primary", onClick: apply, disabled: busy }, busy ? "更新中…" : `更新到 v${data.latest}`) : null,
934
989
  data.hasUpdate && data.command ? Button({ variant: data.canApply ? "ghost" : "primary", onClick: copy, title: data.command }, "复制更新命令") : null),
935
990
  data.hasUpdate ? (data.notes ? h("pre", { className: "fs-report" }, data.notes)
936
991
  : h("p", { className: "fs-row-meta" },
937
992
  h("a", { href: data.notesUrl, target: "_blank", rel: "noopener noreferrer" }, "GitHub Releases"))) : null,
993
+ // 开发目录(link)安装:npm 版不会覆盖它 ⇒ 这里的「更新」是 git pull + 重启。
994
+ // 只是**追加一句说明**,不去替代上面那个按钮(宿主说行就行)。
995
+ data.installMode === "dev" ? Row({ title: "开发目录安装", desc: "npm 上的新版本不会覆盖这个目录,要更新在这里 git pull 之后重启 DSH" },
996
+ Button({ variant: "ghost", onClick: copyDev, title: devCommand }, "复制 git pull 命令"),
997
+ devPath === "" ? null : Muted(devPath)) : null,
938
998
  Row({ title: "自动检查更新", desc: "只提示,不会自动安装;点「更新到」才装,装完重启 DSH 生效" },
939
999
  h(Switch, { checked: data.autoCheck !== false, onChange: toggle, label: "自动检查更新" })));
940
1000
  }
@@ -1050,6 +1110,7 @@ window.__ModuleLoader__.load({
1050
1110
  : subtab === "version" ? h(Boundary, { name: "版本" }, h(UpdateBar, { notify, onUpdateState: setUpdateAvailable }))
1051
1111
  : subtab === "retrieval" ? h(RetrievalPane, { data: retrieval, refresh: loadRetrieval, notify })
1052
1112
  : subtab === "life" ? h(LifePane, { data: life, refresh: loadLife, notify })
1113
+ : subtab === "relay" ? h(RelayPane, { data: life, refresh: loadLife, notify })
1053
1114
  : ["people", "memories", "recall-test", "weekly", "archives", "backups"].includes(subtab) ? h(ChunkTab, { file: "client.soul.js", pick: (m) => m.InspectorPane, failText: "记忆管理加载失败", section: subtab, notify })
1054
1115
  : ["activity", "stickers", "slang"].includes(subtab) ? h(ChunkTab, { file: "client.soul.js", pick: (m) => m.ActivityPane, failText: "动态加载失败", section: subtab, notify })
1055
1116
  : ["habits", "groups", "chat-models", "diary"].includes(subtab) ? h(ChunkTab, { file: "client.behavior.js", pick: (m) => m.BehaviorPane, failText: "习惯页加载失败", section: subtab === "chat-models" ? "models" : subtab, notify })
@@ -101,6 +101,14 @@ export function fishSoulConfigSchema(z) {
101
101
  expressions: z.boolean().default(true), // 学「什么场合怎么说」(只学别人的话、不带人名)
102
102
  privateChats: z.boolean().default(true) // 好友私聊也学(只在那个私聊里用)
103
103
  }).default({}),
104
+ // 熟人传话:白名单里的人 A 托她给白名单里的 B 带一句话(默认关)。
105
+ // 白名单按平台身份(QQ 号 / B站 UID / 抖音 uid)精确匹配,昵称不参与 —— 同名可冒充。
106
+ // 发出的消息自动带来源前缀,B 知道是谁托带的,她不能匿名传话。
107
+ relay: z.object({
108
+ enabled: z.boolean().default(false),
109
+ allowList: z.array(z.string()).default([]), // 白名单(平台 uid,一行一个);空 = 谁都不能用
110
+ perDay: z.number().default(5) // 每个发起人每天最多带几条
111
+ }).default({}),
104
112
  tools: z.object({
105
113
  web: z.object({ // 让她能上网查东西(默认关):DSH 自带的 web_search,或自己填的搜索 API key
106
114
  enabled: z.boolean().default(false),
@@ -168,6 +176,10 @@ export function fishSoulConfigSchema(z) {
168
176
  // #75:自走日程开关。关掉 = 不生成日程、不注入时段、不用忙/闲卡住主动与刷视频
169
177
  scheduleEnabled: z.boolean().default(true),
170
178
  shareMaxPerDay: z.number().default(2), // 刷到想分享的视频,一天最多主动发几条
179
+ shareVideos: z.boolean().default(true), // 分享视频总开关(以前代码读它但 schema 里没有 ⇒ 读不到,等于写不了)
180
+ // #133:最近 N 天没分享过就主动挑一条(0 = 关)。分享原本只靠模型标 [分享],
181
+ // 而提示词明说「大多数视频不用」⇒ 实测她几乎不标,分享待办长期为 0。
182
+ shareFallbackDays: z.number().default(2),
171
183
  targets: z.object({
172
184
  masterCanonicalId: z.string().default('user:master'),
173
185
  masterPrivateChannelId: z.string().default(''),
@@ -105,8 +105,10 @@ export class DouyinBrowser {
105
105
  * @param {import('./douyin-http.js').DouyinHttp} [deps.http] 纯 HTTP 客户端(http 模式用)
106
106
  * @param {object} [deps.timing] 页面操作的时间上限(eval / send / next 的总预算)
107
107
  */
108
- constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, note, http, frames, timing = {} }) {
108
+ constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, frames, timing = {} }) {
109
109
  this.share = share ?? null;
110
+ // #133:同上 —— 漏了这个参数兜底就是死代码。
111
+ this.shareFallback = shareFallback ?? null;
110
112
  this.note = note ?? null;
111
113
  this.framesOf = frames ?? null; // 抽九宫格看画面(可缺:没有就只读文字)
112
114
  this.db = db;
@@ -11,8 +11,8 @@ import { isIdentityKey } from './douyin-conversation.js';
11
11
  import { findVideoRefs } from './browse.js';
12
12
  import { findDouyinRefs } from './douyin-browse.js';
13
13
  import { prepareImage } from './imageconv.js';
14
- import { sanitizeName } from './channels/onebot.js';
15
- import { mediaTypeOf, isInside, fetchImageBytes, splitChannelId, service } from './gateway-util.js';
14
+ import { sanitizeName, sanitizeUserText } from './channels/onebot.js';
15
+ import { mediaTypeOf, isInside, fetchImageBytes, splitChannelId, service, normalizeRelayId } from './gateway-util.js';
16
16
 
17
17
  const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
18
18
  const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
@@ -23,6 +23,50 @@ const DOUYIN_EMOJI_RE = /^\[([\u4e00-\u9fa5A-Za-z0-9]{1,8})\]$/;
23
23
  const VOICE_TAG_RE = /^\s*\[语音\]\s*/;
24
24
  const platformName = (channelId) => (String(channelId).startsWith('bili:') ? 'B站' : '抖音');
25
25
 
26
+ /** 传话计数写回:失败不影响已经发出去的消息。 */
27
+ function setKvRelay(db, key, n) {
28
+ try {
29
+ db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, JSON.stringify(n));
30
+ } catch { /* 记不下来不影响已经发出去的消息 */ }
31
+ }
32
+
33
+ /** 按平台 uid 查显示名;查不到返回 null(只用于来源前缀,不参与授权)。 */
34
+ function relayPersonName(db, relayId) {
35
+ const [plat, id] = relayId.split(':');
36
+ let row = null;
37
+ try {
38
+ if (plat === 'qq') row = db.prepare('SELECT display_name FROM person WHERE qq_uin = ?').get(id);
39
+ else if (plat === 'bili') row = db.prepare('SELECT display_name FROM person WHERE bili_uid = ?').get(id);
40
+ else if (plat === 'douyin') row = db.prepare('SELECT display_name FROM person WHERE douyin_uid = ?').get(`douyin:${id}`);
41
+ } catch { /* 读不到就当没名字 */ }
42
+ const name = String(row?.display_name ?? '').trim();
43
+ return name === '' ? null : name;
44
+ }
45
+
46
+ /** 抖音会话名(`douyin:<uid>` → 游标里记的真实昵称);查不到返回 null(不猜)。 */
47
+ function relayDouyinName(db, relayId) {
48
+ try {
49
+ const identity = relayId.startsWith('douyin:') ? relayId : `douyin:${relayId}`;
50
+ const rows = db.prepare("SELECT value FROM kv WHERE key LIKE 'douyin.conv.%' AND key NOT LIKE 'douyin.convId.%'").all();
51
+ for (const r of rows) {
52
+ let v = null;
53
+ try { v = JSON.parse(r.value); } catch { continue; }
54
+ if (String(v?.identity ?? '') !== identity) continue;
55
+ const name = String(v?.name ?? '').trim();
56
+ if (name !== '') return name;
57
+ }
58
+ } catch { /* 读不到就当没有 */ }
59
+ return null;
60
+ }
61
+
62
+ /** relayId → 给别人看的 channelId(journalOut / note 用)。 */
63
+ function relayChannelOf(relayId) {
64
+ const [plat, id] = relayId.split(':');
65
+ if (plat === 'qq') return `private:${id}`;
66
+ if (plat === 'bili') return `bili:${id}`;
67
+ return `douyin:${id}`;
68
+ }
69
+
26
70
  /**
27
71
  * 共同校验 QQ 和私信出站图片;返回实际文件路径,失败关闭。
28
72
  *
@@ -685,5 +729,94 @@ export const mediaMethods = {
685
729
  afterRelay(channelId, text, platform) {
686
730
  try { this.soul.journalOut?.(channelId, text); } catch { /* 记日志失败不影响已经发出去的消息 */ }
687
731
  this.note('relay', { channelId, text, reason: `主人让去${platform === 'bili' ? 'B站' : '抖音'}发的` });
732
+ },
733
+
734
+ /**
735
+ * 熟人传话:白名单里的人托她给白名单里的另一个人带一句话。默认关(`relay.enabled`)。
736
+ *
737
+ * 四道闸:① 开关 ② 发起人在白名单 ③ 收件人在白名单 ④ 发起人当天没超 `relay.perDay` 条。
738
+ *
739
+ * 白名单按平台 uid 精确匹配(`qq:` / `bili:` / `douyin:` + 数字),昵称不参与 ——
740
+ * 同名可以冒充,改名又会对不上。
741
+ *
742
+ * 发出的消息自动带「【xx托我带句话】」前缀:收件人知道这不是她自己的话、也知道是谁托的,
743
+ * 她没法匿名传话。
744
+ *
745
+ * @returns {Promise<{ok: boolean, delivered: boolean, reason: string}>}
746
+ */
747
+ async relayToFriend(fromId, toId, text) {
748
+ const said = String(text ?? '').trim();
749
+ if (said === '') return { ok: false, delivered: false, reason: '内容是空的,没带' };
750
+ const rcfg = this.relayConfig();
751
+ if (rcfg.enabled !== true) return { ok: false, delivered: false, reason: '传话功能没开(设置页「日常」→ 传话)' };
752
+ const from = normalizeRelayId(fromId);
753
+ const to = normalizeRelayId(toId);
754
+ if (from === null) return { ok: false, delivered: false, reason: '认不出是谁要传话(要 QQ 号 / B站 / 抖音的数字 uid)' };
755
+ if (to === null) return { ok: false, delivered: false, reason: '认不出要带给谁(要 QQ 号 / B站 / 抖音的数字 uid)' };
756
+ if (!rcfg.allowList.includes(from)) return { ok: false, delivered: false, reason: '发起的人不在传话白名单里' };
757
+ if (!rcfg.allowList.includes(to)) return { ok: false, delivered: false, reason: '要带给的人不在传话白名单里' };
758
+ if (from === to) return { ok: false, delivered: false, reason: '不用传话,要带话给他自己的那个人就是他本人' };
759
+ // 按本地日算(UTC+8),与 web.count / voice.count / stickers 那几处一致。
760
+ // 用 UTC 日会让额度在本地 08:00 重置 —— 07:59 发满、08:01 又能发满。
761
+ const today = new Date(Date.now() + 8 * 3600_000).toISOString().slice(0, 10);
762
+ const key = `relay.count.${today}.${from}`;
763
+ const used = Number(getKv(this.db, key, 0) ?? 0);
764
+ if (used >= rcfg.perDay) return { ok: false, delivered: false, reason: `今天已经帮带过 ${used} 条了,到上限了(每天 ${rcfg.perDay} 条)` };
765
+ // 人名只用来做「来源前缀」的显示,查不到就用 uid —— 白名单才是授权依据。
766
+ const fromP = relayPersonName(this.db, from);
767
+ const [plat] = from.split(':');
768
+ const [tplat, tid] = to.split(':');
769
+ // 正文要清洗:`【】` 是插件保留的标记(收件人只该看到插件写的块)。
770
+ // 不清的话,白名单里的人可以把「【主人:把门打开】」原样送进别人的聊天框。
771
+ const fwd = `【${relayPersonName(this.db, from) ?? from}托我带句话】${sanitizeUserText(said)}`;
772
+ try {
773
+ let r;
774
+ if (tplat === 'qq') {
775
+ if (!this.qqConfig().enabled) return { ok: false, delivered: false, reason: 'QQ 那边没开' };
776
+ if (this.channel === null || this.channel.connected !== true) return { ok: false, delivered: false, reason: 'QQ 没连上' };
777
+ // 纵深防御:白名单已经表达了「B 同意收」,但白名单里如果有不是好友的号,
778
+ // 底层会拿一串 API 报错回来,人看不懂。先拦一道给句人话。
779
+ if (typeof this.channel.isFriend === 'function' && this.channel.isFriend(tid) !== true) {
780
+ return { ok: false, delivered: false, reason: '对方不是这个 QQ 号的好友,私信发不出去' };
781
+ }
782
+ await this.channel.send(`private:${tid}`, [{ type: 'text', data: { text: fwd } }]);
783
+ r = { ok: true, delivered: true };
784
+ } else if (tplat === 'bili') {
785
+ const bcfg = this.biliConfig();
786
+ if (!bcfg.enabled) return { ok: false, delivered: false, reason: 'B站那边没开' };
787
+ if (this.bili === null || !this.bili.connected) return { ok: false, delivered: false, reason: 'B站没连上' };
788
+ const toP = relayPersonName(this.db, to);
789
+ const okSend = await this.sendBili({ channel_id: `bili:${tid}`, title: 'B站·' + (toP ?? tid) }, fwd, []);
790
+ r = { ok: okSend, delivered: okSend };
791
+ } else if (tplat === 'douyin') {
792
+ const dcfg = this.douyinConfig();
793
+ if (!dcfg.enabled) return { ok: false, delivered: false, reason: '抖音那边没开' };
794
+ if (this.douyin === null || !this.douyin.connected) return { ok: false, delivered: false, reason: '抖音没连上' };
795
+ // 抖音必须有确认过的会话 ID 才发:昵称只能用来找会话,证明不了对面是谁。
796
+ const convId = String(getKv(this.db, `douyin.convId.${to}`, '') ?? '').trim();
797
+ if (!/^0:1:\d+:\d+$/.test(convId)) return { ok: false, delivered: false, reason: '要带给的人还没跟她确认过抖音会话,没法发' };
798
+ // 会话名要用**游标里的真实昵称**(抖音靠它 enterChat 找会话),
799
+ // 不能用 person.display_name —— 那是消息昵称,主人还能在「人物与关系」里改,
800
+ // 改了就跟抖音上的名字对不上,发不出去。
801
+ const toName = relayDouyinName(this.db, to);
802
+ if (toName === null) return { ok: false, delivered: false, reason: '认不出这个抖音会话叫什么名字(还没读到过它的会话列表),暂时发不了' };
803
+ const row = { channel_id: `douyin:${toName}`, title: '抖音·' + toName };
804
+ const dr = await this.sendDouyin(row, fwd, [], convId);
805
+ r = { ok: dr.ok === true, delivered: dr.delivered === true, reason: dr.error ?? '' };
806
+ } else {
807
+ return { ok: false, delivered: false, reason: '只认 qq / bili / douyin 的 uid' };
808
+ }
809
+ if (r.ok === true) {
810
+ setKvRelay(this.db, key, used + 1);
811
+ try { this.soul.journalOut?.(relayChannelOf(to), fwd); } catch { /* 日志失败不影响 */ }
812
+ const toP = relayPersonName(this.db, to);
813
+ this.note('relay', { channelId: relayChannelOf(to), text: fwd, reason: `${fromP ?? from} 让带给 ${toP ?? to} 的(${plat})` });
814
+ }
815
+ return { ok: r.ok === true, delivered: r.delivered === true, reason: r.ok === true ? '' : (r.reason || '发送时报错了,看日志') };
816
+ } catch (error) {
817
+ const msg = String(error instanceof Error ? error.message : error);
818
+ this.log('error', `[fish-soul] 传话失败:${msg}`);
819
+ return { ok: false, delivered: false, reason: msg.slice(0, 120) };
820
+ }
688
821
  }
689
822
  };
@@ -112,6 +112,46 @@ export function interjectConfig(raw) {
112
112
  };
113
113
  }
114
114
 
115
+ /** 传话用的平台身份:把 "qq:123" / "bili:456" / "douyin:789" 规整成统一形态;认不出返回 null。
116
+ * 纯数字默认当 QQ 号(群里最常这么写)。 */
117
+ export function normalizeRelayId(raw) {
118
+ const s = String(raw ?? '').trim();
119
+ if (!s) return null;
120
+ if (/^\d+$/.test(s)) return `qq:${s}`;
121
+ const m = /^(qq|bili|douyin):(\d+)$/.exec(s);
122
+ return m === null ? null : `${m[1]}:${m[2]}`;
123
+ }
124
+
125
+ /** 传话工具的收件人解析:`to` + `platform` → `qq:123` / `bili:123` / `douyin:123`。
126
+ *
127
+ * 两种写法都收:「带前缀」(`bili:12345`,面板里就是这么写的)和「纯数字 + platform」。
128
+ * @returns {{ok: true, id: string} | {ok: false, error: string}}
129
+ * 🔴 不认识的 platform **必须拒**,不能静默降级成 qq —— 那会把话发给
130
+ * 「另一个平台上恰好同号的人」。
131
+ */
132
+ export function parseRelayTarget(toRaw, platformRaw) {
133
+ const raw = String(toRaw ?? '').trim();
134
+ if (raw === '') return { ok: false, error: '没带收件人(要给对方的平台 uid),话说不了。' };
135
+ if (/^(qq|bili|douyin):\d+$/.test(raw)) return { ok: true, id: raw };
136
+ if (/^\d+$/.test(raw)) {
137
+ const p = platformRaw === undefined || platformRaw === null || String(platformRaw).trim() === ''
138
+ ? 'qq' : String(platformRaw).trim().toLowerCase();
139
+ if (!['qq', 'bili', 'douyin'].includes(p)) {
140
+ return { ok: false, error: `不认识的平台「${String(platformRaw).trim()}」,只认 qq / bili / douyin,这次没带。` };
141
+ }
142
+ return { ok: true, id: `${p}:${raw}` };
143
+ }
144
+ return { ok: false, error: `收件人「${raw}」看不出是哪个平台的号。要么给纯数字 + platform,要么写成 qq:123 / bili:123 / douyin:123。` };
145
+ }
146
+
147
+ /** 宿主 user/message 事件里的正文(content 可能是字符串,也可能是 block 数组)。 */
148
+ export function textOfUserMessage(message) {
149
+ const content = message?.content;
150
+ if (typeof content === 'string') return content;
151
+ if (!Array.isArray(content)) return '';
152
+ return content.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim();
153
+ }
154
+
115
155
  /** channel_id → 平台:bili:<UID> 是 B站私信,douyin:<名字> / douyin-group:<群名> 是抖音私信 / 群聊,其余(private:/group:)是 QQ。 */
116
156
  export function platformOf(channelId) {
117
157
  const s = String(channelId ?? '');
package/lib/gateway.js CHANGED
@@ -37,7 +37,7 @@ import { applyAttachments, attachmentConfig } from './attachments.js';
37
37
  import { parseCollect } from './stickers.js';
38
38
  import { UNHEARD } from './voice.js';
39
39
  import { saveVoiceFile, voiceIncomingEpoch, audioExt } from './voice-files.js';
40
- import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow } from './gateway-util.js';
40
+ import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow, normalizeRelayId, textOfUserMessage } from './gateway-util.js';
41
41
  import { mediaMethods } from './gateway-media.js';
42
42
  import { Outbox, classifySendError } from './outbox.js';
43
43
  import { safeDownload } from './safe-download.js';
@@ -56,8 +56,10 @@ const OUR_SOURCES = new Set([SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DO
56
56
  export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget'];
57
57
  /** 跨平台转达:主人在 QQ 私聊里让她去抖音 / B站 私信自己一条。 */
58
58
  export const RELAY_TOOL = 'send_elsewhere';
59
+ /** 熟人传话:白名单里的人托她给白名单里的另一个人带句话(默认关)。 */
60
+ export const RELAY_FRIEND_TOOL = 'relay_to_friend';
59
61
  /** 聊天会话里放行的插件工具(记忆 + 跨平台转达)。 */
60
- export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL];
62
+ export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL];
61
63
  /** 宿主的联网工具:设置里打开「让她能上网查」才放行(护栏按天限次数)。 */
62
64
  export const WEB_TOOLS = ['web_search', 'web_fetch'];
63
65
  /** 自己填 key 的搜索服务(插件注册的工具) */
@@ -784,6 +786,18 @@ export class ChatGateway {
784
786
  WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n));
785
787
  }
786
788
 
789
+ /** 传话配置:熟人托她给另一个人带句话(默认关,白名单按平台 uid 精确匹配)。 */
790
+ relayConfig() {
791
+ const r = this.getConfig().relay ?? {};
792
+ return {
793
+ enabled: r.enabled === true,
794
+ // 手改配置文件可能写成裸数字(`10001`)—— 归一成 `qq:10001` 再比,
795
+ // 不然形式对不上就静默失效(主人以为配了,实际一条也发不出去)。
796
+ allowList: Array.isArray(r.allowList) ? r.allowList.map((x) => normalizeRelayId(x)).filter((x) => x !== null) : [],
797
+ perDay: Number.isFinite(Number(r.perDay)) ? Math.max(1, Math.min(50, Math.floor(Number(r.perDay)))) : 5
798
+ };
799
+ }
800
+
787
801
  /** #37 聊天会话的工具放行档位:memory(默认,只放记忆 + 联网)| master(主人私聊全放开)| all(所有会话全放开)。 */
788
802
  sessionAllowMode() {
789
803
  const v = String(this.getConfig().tools?.sessionAllow ?? 'memory').trim().toLowerCase();
@@ -1676,7 +1690,14 @@ export class ChatGateway {
1676
1690
  const pending = this.pendingVoicePaths?.get(String(msg?.id ?? ''));
1677
1691
  st.voicePaths = kind === SOURCE_QQ && pending?.sessionId === sessionId && Date.now() - pending.at <= 300_000 ? pending.paths : [];
1678
1692
  if (pending) this.pendingVoicePaths.delete(String(msg.id));
1679
- } else if (kind === 'user') { st.fromUs = false; st.dshTyped = true; st.voicePaths = []; } // #78:DSH 桌面端打字,不外发但要记动态
1693
+ } else if (kind === 'user') {
1694
+ st.fromUs = false; st.dshTyped = true; st.voicePaths = [];
1695
+ // #78:主人自己打的字也记下来。动态页原来只显示她的发言 ⇒ 主人看到
1696
+ // 「动态里只有一条 DSH,内容是她的发言,我的发言去哪了」。
1697
+ // 记忆整理不受影响(他的发言经 beginTurn 的 speakers 进 journal),
1698
+ // 缺的是动态页这一轮的上下文。
1699
+ st.userText = textOfUserMessage(msg);
1700
+ }
1680
1701
  // 其他宿主上下文(runtime-context / model-selection 等):不动 fromUs ——
1681
1702
  // 它们不是我们发的消息,但也不是真人打字,重置会把 B站/抖音 的回复憋回去(smoke #13 守着)
1682
1703
  // 共享会话里一个会话对应多个通道(QQ + B站):这一轮从哪个通道进来的,来源里也带着 ——
@@ -1752,6 +1773,9 @@ export class ChatGateway {
1752
1773
  this.note('dsh', {
1753
1774
  channelId: st.channelId ?? this.bound.get(sessionId)?.channel_id ?? '',
1754
1775
  text: String(st.text ?? '').slice(0, 60),
1776
+ // 主人这一轮说了什么也带上(#78):动态页只显示她的发言,
1777
+ // 主人会以为自己的话丢了。带上之后这一轮是完整的一问一答。
1778
+ who: String(st.userText ?? '').trim() === '' ? '' : '主人:' + String(st.userText).trim().slice(0, 40),
1755
1779
  reason: '在 DSH 里聊的,不外发',
1756
1780
  memories: recall.memories ?? [],
1757
1781
  recallAt: recall.at ?? 0,
package/lib/index.js CHANGED
@@ -15,7 +15,7 @@ import { readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs';
15
15
  import { loadHostDeps } from './hostdeps.mjs';
16
16
  import {
17
17
  openDatabase, configPath, fishSoulDir, resolveOrCreatePerson, resolveOrCreateBiliPerson,
18
- findPersonByQq, findPersonByBili, readVecMeta, getKv, setKv, getProfile, ensureMasterPerson
18
+ findPersonByQq, findPersonByBili, findPersonByDouyin, readVecMeta, getKv, setKv, getProfile, ensureMasterPerson
19
19
  } from './db.js';
20
20
  import { WeeklyCompressor } from './weekly.js';
21
21
  import { MemoryArchive } from './storage.js';
@@ -47,9 +47,9 @@ 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, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf
50
+ ChatGateway, SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN, CHAT_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, WEB_TOOLS, OWN_WEB_TOOL, splitChannelId, sessionChannelOf
51
51
  } from './gateway.js';
52
- import { platformLabelOf, platformOf } from './gateway-util.js';
52
+ import { platformLabelOf, platformOf, parseRelayTarget } from './gateway-util.js';
53
53
  import { VirtualClock } from './clock.js';
54
54
  import { EmbeddingClient, VectorWorker, recall, recallSync, vectorRanks } from './retrieval.js';
55
55
  import { LifeEngine } from './life.js';
@@ -320,7 +320,7 @@ async function startup(ctx, config, { log, gate }) {
320
320
  });
321
321
  const browser = new BiliBrowser({
322
322
  db, clock, client: biliClient, getConfig: biliCfg, callLlm: llmRouter.bound('browse'), worker, log,
323
- share: (x) => life.queueShare(x), note: (k, x) => gateway?.note(k, x),
323
+ share: (x) => life.queueShare(x), shareFallback: (x) => life.queueShareFallback(x), note: (k, x) => gateway?.note(k, x),
324
324
  persona: () => ({ name: persona.name, brief: personaBrief() }),
325
325
  // 抽帧看画面(bili.browse.frames 开才用):一条失败不影响她看完这条视频
326
326
  // 超时 60s:CDN 卡住时 ffmpeg 永久挂起会拖死整轮 watch(),到点 kill 退回纯文字
@@ -380,7 +380,7 @@ async function startup(ctx, config, { log, gate }) {
380
380
  // 抽帧看画面(douyin.browse.frames 开才用):play_addr 直链 → ffmpeg 九宫格。
381
381
  // 超时 90 秒(抖音 CDN 会挂);一条失败不影响她看完这条,照旧只看文字。
382
382
  frames: (v) => douyinFrames(v.urls, { id: v.id, durationMs: v.durationMs, signal: AbortSignal.timeout(90_000) }),
383
- share: (x) => life.queueShare(x), note: (k, x) => gateway?.note(k, x),
383
+ share: (x) => life.queueShare(x), shareFallback: (x) => life.queueShareFallback(x), note: (k, x) => gateway?.note(k, x),
384
384
  persona: () => ({ name: persona.name, brief: personaBrief() })
385
385
  });
386
386
  // 抖音自己发图文 / 回评论(默认都关;走专用浏览器,尽力而为)
@@ -582,7 +582,35 @@ async function startup(ctx, config, { log, gate }) {
582
582
  };
583
583
  }
584
584
 
585
- /** 工具调用:按调用所在会话(toolCtx.agent.id)认人;认不出就是 unknown(不读写任何人的记忆)。 */
585
+ /**
586
+ * 传话工具:从会话反查发起人的平台 uid(qq:123 / bili:456 / douyin:789);认不出返回空串。
587
+ *
588
+ * 抖音这一支:会话里消息的 senderId 不是当前说话人就是机器人自己。
589
+ * 用 conversationIdentity 把「我方 uid / 对方 uid」从 convId 里分出来,
590
+ * 对方 uid = 当前在跟她说话的那个人。
591
+ */
592
+ function relaySenderId(session) {
593
+ const channelId = String(session?.channelId ?? '');
594
+ if (channelId === '') return '';
595
+ const [kind, id] = splitChannelId(channelId);
596
+ if (kind === 'private') {
597
+ const person = findPersonByQq(db, id);
598
+ return person?.qq_uin ? `qq:${person.qq_uin}` : '';
599
+ }
600
+ if (kind === 'bili') {
601
+ const person = findPersonByBili(db, id);
602
+ return person?.bili_uid ? `bili:${person.bili_uid}` : '';
603
+ }
604
+ if (kind === 'douyin') {
605
+ // 抖音的 channel_id 是昵称(`douyin:<昵称>`),**不是身份** —— 昵称能改、能撞名。
606
+ // 真实身份要从游标反查(`douyin.conv.<sha1(昵称)>` 里的 identity,那是用会话 ID 推出来的)。
607
+ // 复用网关已有的实现,别在这里再写一份(PR #96 的冒充洞就是按昵称认人)。
608
+ const identity = String(gateway?.douyinIdentityOfChannel?.(channelId) ?? '').trim();
609
+ return /^douyin:\d+$/.test(identity) ? identity : '';
610
+ }
611
+ return '';
612
+ }
613
+
586
614
  function sessionForTool(toolCtx, speakerName) {
587
615
  const id = toolCtx?.agent?.id ?? toolCtx?.sessionId;
588
616
  const activeChannel = gateway?.turns?.get(String(id))?.channelId;
@@ -1178,6 +1206,7 @@ async function startup(ctx, config, { log, gate }) {
1178
1206
  step(STARTUP_STEPS[14]);
1179
1207
  registerRoutes(ctx, {
1180
1208
  gate,
1209
+ ctx, // /update/ 那组路由要靠它找宿主的 plugin-manager 服务(一键更新)
1181
1210
  db, clock, embedder, embeddingCfg, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial, douyinSocial,
1182
1211
  douyin, douyinHost, douyinBrowser, backup, historyImporter, updater, worldBooks,
1183
1212
  llmRouter, voice, stickers, slang, persona, reloadPersona, webConfig, hasWebTools, webUsedToday, hostWebAvailable, hostWebState, runWebSearch,
@@ -1254,7 +1283,7 @@ async function startup(ctx, config, { log, gate }) {
1254
1283
  }
1255
1284
  if (exec.name === 'run_code') return `聊天会话里不能运行代码(放开工具也不放 run_code:它能跑任意程序)`;
1256
1285
  if (sessionOpen(id)) return undefined; // #37 主人/全部放开:宿主工具都放
1257
- return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达和上网查;设置页「模型」里可以放开)`;
1286
+ return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达、熟人传话和上网查;设置页「模型」里可以放开)`;
1258
1287
  });
1259
1288
  gateway.voiceGuardReady = true;
1260
1289
  return () => { gateway.voiceGuardReady = false; off?.(); };
@@ -1460,6 +1489,43 @@ async function startup(ctx, config, { log, gate }) {
1460
1489
  }
1461
1490
  })), 'dsh-fish-soul: send_elsewhere');
1462
1491
 
1492
+ // ── 工具:relay_to_friend(白名单里的人 A 托她给白名单里的 B 带句话;默认关)──
1493
+ ctx.effect(() => ctx.tools.register(defineTool({
1494
+ name: RELAY_FRIEND_TOOL,
1495
+ description: '帮当前说话的人给另一个熟人带一句话(对方会收到「xx 托我带句话:…」)。' +
1496
+ '只有对方明确要求(「帮我跟 xx 说一声」「带句话给 xx」这类)时才用,别自己找机会用。' +
1497
+ '收件人必须给平台 uid(QQ 号 / B站 UID / 抖音 uid),昵称会发错人所以不认。' +
1498
+ '两边都得在主人配的传话白名单里才能用,发不出去会告诉你原因,照实跟对方说,别编。',
1499
+ parameters: objectSchema({
1500
+ to: { type: 'string', required: true, description: "收件人的平台 uid。两种写法都收:纯数字 + platform(如 to='12345', platform='qq'),或直接带前缀(如 to='bili:12345')。白名单里怎么写的就照抄" },
1501
+ platform: { type: 'string', description: "收件人在哪个平台:'qq' | 'bili' | 'douyin'。to 已经带前缀时可以不给;两个都给就以前缀为准。**不认识的平台值会被拒**(不会默认成 QQ,那样可能把话发给另一个人)" },
1502
+ text: { type: 'string', required: true, description: '要带的那句话(一段,照对方的意思写,别加引号)' }
1503
+ }),
1504
+ output: textOutput,
1505
+ async execute(args, toolCtx) {
1506
+ if (gateway === null) return '网关没起来,带不了话。';
1507
+ const session = sessionForTool(toolCtx);
1508
+ // 发起人:从会话绑定身份反查平台 uid。认不出是谁就不发 —— 白名单比的是 uid,
1509
+ // 认不出 = 给不了 uid,宁可拒了也不能按昵称猜(昵称可以随便改)。
1510
+ const fromId = relaySenderId(db, session);
1511
+ if (fromId === '') return '认不出你是谁(这个会话没绑到认识的人),带不了话。';
1512
+ const target = parseRelayTarget(args.to, args.platform);
1513
+ if (target.ok !== true) return target.error;
1514
+ const toId = target.id;
1515
+ const text = String(args.text ?? '').trim();
1516
+ if (text === '') return '要带的话是空的,没发。';
1517
+ try {
1518
+ const r = await gateway.relayToFriend(fromId, toId, text);
1519
+ if (!r.ok) return `没带到:${r.reason}。`;
1520
+ return r.delivered ? '带到了。' : '发出去了,但回读没看到,可能没真到。';
1521
+ } catch (error) {
1522
+ const msg = String(error instanceof Error ? error.message : error);
1523
+ log('warn', `[fish-soul] 传话失败:${msg}`);
1524
+ return `没带成:${msg.slice(0, 120)}。`;
1525
+ }
1526
+ }
1527
+ })), 'dsh-fish-soul: relay_to_friend');
1528
+
1463
1529
  // ── 工具:fish_search(自己填 key 的搜索服务;只在鱼的聊天会话里能用,开关 / 次数由上面的护栏管)──
1464
1530
  ctx.effect(() => ctx.tools.register(defineTool({
1465
1531
  name: OWN_WEB_TOOL,
package/lib/life.js CHANGED
@@ -45,7 +45,12 @@ const PENDING_MAX_ATTEMPTS = PENDING_RETRY_STEPS_VIRTUAL_MS.length;
45
45
  const SURFACED_RECYCLE_VIRTUAL_MS = 6 * 3600_000;
46
46
  const RESTORE_INTERACTION_WINDOW_MS = 7 * 86_400_000;
47
47
  /** 刷到想分享的:排进待办,过了这么久(虚拟)还没发出去就算了(隔天再分享像翻旧账) */
48
- const SHARE_TTL_VIRTUAL_MS = 4 * 3600_000;
48
+ // 分享待办的时效:12 虚拟小时(以前 4 小时 —— 下午刷到的晚上想发已经过期了,
49
+ // 真机上 2026-11-12 排的那条就是这么变成 expired 的,主人只看到「她没开口」)。
50
+ // ⚠️ 但**不能跨角色日**:12 小时窗口必然跨午夜(16:00 排的能发到次日 04:00),
51
+ // 而待办正文写的是「你刚在X刷到一个视频」—— 隔天早上发出去这话就不成立了。
52
+ // 所以过期判定 = 「超过 TTL」或「不是同一个角色日」,两个条件满足其一就作废。
53
+ const SHARE_TTL_VIRTUAL_MS = 12 * 3600_000;
49
54
  const SHARE_DEFAULT_PER_DAY = 2;
50
55
  /** 她自己起意的待办(占每日主动配额) */
51
56
  const BOT_ORIGINS = new Set(['dream', 'share']);
@@ -341,8 +346,12 @@ export class LifeEngine {
341
346
  */
342
347
  async flushDue(p) {
343
348
  const nowVirtual = this.clock.now();
344
- // 分享过了时效就不发了(下午刷到的视频晚上再发像翻旧账)
345
- this.db.prepare("UPDATE pending SET status = 'expired' WHERE character_id = 'feiyu' AND status = 'pending' AND origin = 'share' AND due_at < ?").run(nowVirtual - SHARE_TTL_VIRTUAL_MS);
349
+ // 分享过了时效就不发了(下午刷到的视频晚上再发像翻旧账;隔天更不行 —— 正文写的是「你刚刷到」)
350
+ this.db.prepare("UPDATE pending SET status = 'expired' WHERE character_id = 'feiyu' AND status = 'pending' AND origin = 'share' AND (due_at < ? OR created_at < ?)").run(
351
+ nowVirtual - SHARE_TTL_VIRTUAL_MS,
352
+ // 当天 00:00(角色时区)之前的排的都作废
353
+ this.roleDayStartMs(nowVirtual)
354
+ );
346
355
  // 顺口提起过、对方没接着聊:过一阵退回 pending 重来,别让提醒就这么没了(#80)
347
356
  this.db.prepare(`
348
357
  UPDATE pending SET status = 'pending', due_at = ?, surfaced_at = NULL
@@ -371,7 +380,7 @@ export class LifeEngine {
371
380
  (day.last_proactive_at === null || day.last_proactive_at === undefined ||
372
381
  nowVirtual - day.last_proactive_at >= PROACTIVE_MIN_GAP_VIRTUAL_MS);
373
382
  if (!botAllowed) return false;
374
- const bot = rows.find((d) => BOT_ORIGINS.has(d.origin) && !(d.origin === 'share' && d.due_at < nowVirtual - SHARE_TTL_VIRTUAL_MS));
383
+ const bot = rows.find((d) => BOT_ORIGINS.has(d.origin) && !(d.origin === 'share' && this.shareExpired(d, nowVirtual)));
375
384
  if (bot === undefined) return false;
376
385
  await this.deliverOne(bot, nowVirtual);
377
386
  return true;
@@ -400,6 +409,9 @@ export class LifeEngine {
400
409
  this.lastProactiveReal.set(platform, Date.now());
401
410
  if (ok) {
402
411
  this.db.prepare("UPDATE pending SET status = 'done' WHERE id = ?").run(d.id);
412
+ // #133:分享**真的发出去了**才记「上次分享」(分平台)。
413
+ // 分平台是因为抖音分享一次不该把 B站的兜底也压掉 —— 主人报的就是 B站。
414
+ if (d.origin === 'share') this.recordShareSent(d.id, nowVirtual);
403
415
  if (botInitiated) {
404
416
  this.db.prepare(`
405
417
  UPDATE day SET proactive_count = proactive_count + 1, last_proactive_at = ?
@@ -480,7 +492,7 @@ export class LifeEngine {
480
492
  `).all();
481
493
  for (const r of rows) {
482
494
  if (!this.isWhitelisted(r.channel_id, p, r.origin)) continue;
483
- if (r.origin === 'share' && r.due_at < nowVirtual - SHARE_TTL_VIRTUAL_MS) continue;
495
+ if (r.origin === 'share' && this.shareExpired(r, nowVirtual)) continue;
484
496
  return Math.max(0, r.due_at - nowVirtual);
485
497
  }
486
498
  return null;
@@ -590,6 +602,40 @@ export class LifeEngine {
590
602
  this.note('browse', { title: '抖音', reason: '想刷抖音,但抖音浏览器没开或没登录,这次先刷 B站' });
591
603
  }
592
604
 
605
+ /**
606
+ * 角色时区(UTC+8)当天 00:00 对应的虚拟毫秒。
607
+ * 角色日 = (atMs + 8h) 的 UTC 日期,所以那天的 00:00 往前推 8 小时就是 UTC 起点。
608
+ */
609
+ roleDayStartMs(atMs) {
610
+ const parts = this.clock.getRoleDateParts(atMs);
611
+ const d = String(parts?.dateStr ?? '');
612
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) return 0;
613
+ const utc = Date.UTC(Number(d.slice(0, 4)), Number(d.slice(5, 7)) - 1, Number(d.slice(8, 10)));
614
+ return utc - 8 * 3600_000;
615
+ }
616
+
617
+ /**
618
+ * 一条分享待办是不是已经「过时」了。
619
+ * 两个条件满足其一就作废:① 超过 TTL;② 不是同一个角色日(跨夜了 ——
620
+ * 待办正文写的是「你刚在X刷到」,隔天发出去这话就不成立)。
621
+ */
622
+ shareExpired(row, nowVirtual) {
623
+ if (Number(row?.due_at ?? 0) < nowVirtual - SHARE_TTL_VIRTUAL_MS) return true;
624
+ const dayStart = this.roleDayStartMs(nowVirtual);
625
+ return dayStart > 0 && Number(row?.created_at ?? 0) < dayStart;
626
+ }
627
+
628
+ /**
629
+ * 一条分享待办真的发出去了 ⇒ 记「这个平台上次分享是在什么时候」。
630
+ * @param {number|string} pendingId
631
+ * @param {number} nowVirtual
632
+ */
633
+ recordShareSent(pendingId, nowVirtual) {
634
+ const plat = String(getKv(this.db, `share.platform.${pendingId}`, '') ?? '');
635
+ if (plat === '') return;
636
+ setKv(this.db, `share.lastAt.${plat}`, nowVirtual);
637
+ }
638
+
593
639
  /**
594
640
  * 刷到特别想分享的视频:排一条给主人的主动消息(带链接 + 感受)。
595
641
  * 走主动开口的所有限制(活跃时段、白名单、每日配额、两条之间的间隔),一天最多 proactive.shareMaxPerDay 条(默认 2)。
@@ -632,10 +678,59 @@ export class LifeEngine {
632
678
  // 它漏抄链接、或者干脆回个 [不回],卡片该发还是要发。
633
679
  if (dyChannel !== '') setKv(this.db, `share.intent.${id}`, { videoId, caption: clean(impression, 120), title: clean(title, 60) });
634
680
  setKv(this.db, 'share.day', { date: dateStr, count: count + 1 });
681
+ // 🔴 **「上次分享」记在送达时,不是入队时**(#133 审查):
682
+ // 入队就记的话,一条从没发出去的分享(failed / expired)会把兜底锁死两天 ——
683
+ // 等于把「排了没发出去」这个原 bug 原样复制了一遍。
684
+ // 这里只记「这条待办是哪个平台的」,送达时(deliverOne)才写 lastAt。
685
+ setKv(this.db, `share.platform.${id}`, platform);
635
686
  this.armPendingAlarm();
636
687
  return { ok: true, id };
637
688
  }
638
689
 
690
+ /**
691
+ * 兜底:模型这轮没标 [分享],但好几天没分享过了 —— 主动挑一条排上。
692
+ *
693
+ * 为什么要有这条(#133):分享原本只靠模型在每条视频末尾标 [分享],
694
+ * 而提示词里明说「大多数视频不用」⇒ 真机实测她几乎不标 ⇒ 分享待办长期为 0,
695
+ * 主人看到的就是「她刷了一堆视频,但从不开腔分享」。
696
+ *
697
+ * 门槛是「最近 N 天没分享过」(`proactive.shareFallbackDays`,默认 2,0 = 关):
698
+ * 不设门槛的话每轮都分享,那就成刷屏了。
699
+ *
700
+ * @param {{platform: string, candidates: Array<object>}} input
701
+ * @returns {{ok: boolean, error?: string, id?: number}}
702
+ */
703
+ queueShareFallback({ platform, candidates }) {
704
+ const p = this.getConfig().proactive ?? {};
705
+ const days = Math.floor(Number(p.shareFallbackDays ?? 2)) || 0;
706
+ if (days <= 0) return { ok: false, error: '分享兜底关着' };
707
+ if (p.shareVideos === false) return { ok: false, error: '分享视频关着' };
708
+ const now = this.clock.now();
709
+ // ⚠️ **分平台**:抖音分享一次不该把 B站的兜底也压掉(主人报的就是 B站)。
710
+ // 每日配额 share.day 仍���全局的 —— 那道是「别刷屏」的总闸,跨平台共享是对的。
711
+ const lastAt = Number(getKv(this.db, `share.lastAt.${platform}`, 0) ?? 0);
712
+ // 时钟被回拨 / 从旧备份恢复时 now < lastAt ⇒ 负 delta 会把兜底永久锁死。
713
+ // 这里夹到 0(当成「没分享过」)而不是让负数小于阈值。
714
+ const since = lastAt > 0 ? Math.max(0, now - lastAt) : Number.POSITIVE_INFINITY;
715
+ if (lastAt > 0 && since < days * 24 * 3600_000) {
716
+ return { ok: false, error: `最近 ${days} 天分享过了,不主动补` };
717
+ }
718
+ const list = Array.isArray(candidates) ? candidates : [];
719
+ // 只挑「有感受、没划走」的:没印象的分享出去只是一条链接,主人在 DSH 里点开也没话说
720
+ const chosen = list.find((c) => c && c.skipped !== true && String(c.impression ?? '').trim() !== '');
721
+ if (chosen === undefined) return { ok: false, error: '这轮没有值得分享的' };
722
+ const r = this.queueShare({
723
+ platform,
724
+ title: chosen.title,
725
+ author: chosen.owner ?? chosen.author ?? '',
726
+ url: chosen.url,
727
+ impression: chosen.impression
728
+ });
729
+ // 把挑中的那条带回去(#133 审查):调用方记动态时要用它,
730
+ // 自己重算一遍挑的规则可能不一样(印象为空 / 划走),记出来的书名就跟实际发的不一样。
731
+ return { ...r, chosen };
732
+ }
733
+
639
734
  /** 空闲时段自己刷 B站 / 抖音(一次只刷一个):后台跑,不阻塞 tick;失败只记日志。 */
640
735
  maybeBrowse(day, parts) {
641
736
  if ((this.browse === null && this.douyinBrowse === null) || this.isBrowsing) return;
@@ -930,7 +1025,9 @@ export class LifeEngine {
930
1025
  lastProactiveAt: day?.last_proactive_at ?? null,
931
1026
  locks: { isTickRunning: this.isTickRunning, isDreamRunning: this.isDreamRunning }
932
1027
  },
933
- proactiveConfig: this.getConfig().proactive ?? {}
1028
+ proactiveConfig: this.getConfig().proactive ?? {},
1029
+ // 熟人传话(默认关;面板在「日常」页配白名单)
1030
+ relayConfig: this.getConfig().relay ?? {}
934
1031
  };
935
1032
  }
936
1033
  }
@@ -5,7 +5,7 @@
5
5
  * POST /update/config { autoCheck } 自动检查开关
6
6
  * POST /update/apply 一键更新到上次检查到的最新版(走宿主 plugin-manager,失败它自己回滚)
7
7
  */
8
- import { pluginVersion } from './update-check.js';
8
+ import { pluginVersion, installInfo } from './update-check.js';
9
9
  import { applyUpdate, pluginManagerOf } from './self-update.js';
10
10
 
11
11
  const BODY_MAX = 4 * 1024;
@@ -14,7 +14,14 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam
14
14
  if (!path.startsWith('/update/')) return false;
15
15
  const { updater, saveConfig } = deps;
16
16
  const guard = () => { if (!sameOrigin(req)) { send(403, { ok: false, error: 'forbidden' }); return false; } return true; };
17
- const fallback = () => ({ ok: true, current: pluginVersion(), latest: null, hasUpdate: false, checkedAt: null, checking: false, autoCheck: true, canApply: pluginManagerOf(deps.ctx) !== null });
17
+ // ⚠️ fallback 的字段集要和正常路径**完全一致**(少一个字段,面板就少一块东西)。
18
+ // 这次修的就是「漏字段导致按钮消失」,同一个坑不能留半个。
19
+ const fallback = () => ({
20
+ ok: true, current: pluginVersion(), latest: null, hasUpdate: false, checkedAt: null,
21
+ checking: false, autoCheck: true, source: '', notes: '', notesUrl: '', publishedAt: null, error: '', command: '',
22
+ canApply: pluginManagerOf(deps.ctx) !== null,
23
+ installMode: installInfo().mode, installPath: installInfo().path
24
+ });
18
25
 
19
26
  if (method === 'GET' && path === '/update/state') {
20
27
  if (!guard()) return true;
@@ -32,7 +39,9 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam
32
39
  if (!guard()) return true;
33
40
  if (!updater) { send(200, { ...fallback(), ok: false, error: '更新检查没起来' }); return true; }
34
41
  await updater.check();
35
- send(200, updater.state());
42
+ // ⚠️ 别漏 canApply:面板把整个响应换进 data,漏了它「一键更新」按钮就没了
43
+ // (点一下「检查更新」,按钮凭空消失 —— 主人会以为功能坏了)。
44
+ send(200, { ...updater.state(), canApply: pluginManagerOf(deps.ctx) !== null });
36
45
  return true;
37
46
  }
38
47
  if (method === 'POST' && path === '/update/config') {
@@ -42,7 +51,12 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam
42
51
  const b = JSON.parse(raw || '{}');
43
52
  if (typeof b.autoCheck !== 'boolean') { send(400, { ok: false, error: 'autoCheck 要是 true / false' }); return true; }
44
53
  await saveConfig({ update: { autoCheck: b.autoCheck } });
45
- send(200, updater ? { ...updater.state(), autoCheck: b.autoCheck } : { ...fallback(), autoCheck: b.autoCheck });
54
+ // ⚠️ 刚打开自动检查就查一次:否则那 30 秒的启动机会早就被 autoCheck=false 时烧掉了,
55
+ // 打开开关后要等十几个小时才有下一次 —— 面板继续显示旧结果(正是要消灭的那种陈旧)。
56
+ if (b.autoCheck && updater) { try { await updater.check(); } catch { /* 查不到不影响保存 */ } }
57
+ send(200, updater
58
+ ? { ...updater.state(), autoCheck: b.autoCheck, canApply: pluginManagerOf(deps.ctx) !== null }
59
+ : { ...fallback(), autoCheck: b.autoCheck });
46
60
  return true;
47
61
  }
48
62
  return false;
package/lib/routes.js CHANGED
@@ -104,6 +104,11 @@ export function maskKey(key) {
104
104
  * @param {import('./douyin-browse.js').DouyinBrowser} [deps.douyinBrowser]
105
105
  */
106
106
  export function registerRoutes(ctx, deps) {
107
+ // 🔴 **ctx 必须进 deps**:/update/ 那组路由要靠 `deps.ctx` 找宿主的 plugin-manager 服务
108
+ // (一键更新全靠它)。以前 deps 里没有 ctx ⇒ `deps.ctx` 恒 undefined ⇒
109
+ // canApply 恒 false ⇒ 面板上「更新到」按钮**从来没渲染过**。
110
+ // 放在这里而不是各个调用方,是为了以后新增路由不用再记得传一遍。
111
+ deps.ctx ??= ctx;
107
112
  const { db, clock, embedder, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial } = deps;
108
113
  const logger = log ?? (() => {});
109
114
  /** 进行中的 B站扫码(密钥只留在服务端) */
@@ -366,6 +371,15 @@ export function registerRoutes(ctx, deps) {
366
371
  const idleRealGapMinutes = Number.isFinite(rawRealGap) ? Math.min(1440, Math.max(0, Math.floor(rawRealGap))) : DEFAULT_IDLE_REAL_GAP_MIN;
367
372
  const rawIdleHours = Number(body.idleTriggerHours ?? 6);
368
373
  const idleTriggerHours = Number.isFinite(rawIdleHours) ? Math.min(168, Math.max(0, Math.floor(rawIdleHours))) : 6;
374
+ // 分享相关(#133):每天最多几条 + 几天没分享就主动挑一条(0 = 关)
375
+ // ⚠️ **字段缺失就沿用配置里的现值**,不能拿默认值覆盖 ——
376
+ // 否则任何一次没带这两个字段的保存(比如旧客户端、别的调用方)
377
+ // 都会把主人手写的 0(关掉兜底)悄悄改回 2。
378
+ const curProactive = getConfig().proactive ?? {};
379
+ const rawShareMax = body.shareMaxPerDay === undefined ? curProactive.shareMaxPerDay : Number(body.shareMaxPerDay);
380
+ const shareMaxPerDay = Number.isFinite(Number(rawShareMax)) ? Math.min(20, Math.max(0, Math.floor(Number(rawShareMax)))) : 2;
381
+ const rawFallbackDays = body.shareFallbackDays === undefined ? curProactive.shareFallbackDays : Number(body.shareFallbackDays);
382
+ const shareFallbackDays = Number.isFinite(Number(rawFallbackDays)) ? Math.min(30, Math.max(0, Math.floor(Number(rawFallbackDays)))) : 2;
369
383
  saveConfig({
370
384
  proactive: {
371
385
  enabled: body.enabled !== false,
@@ -374,6 +388,8 @@ export function registerRoutes(ctx, deps) {
374
388
  idleTriggerHours,
375
389
  idleRealGapMinutes,
376
390
  scheduleEnabled: body.scheduleEnabled !== false,
391
+ shareMaxPerDay,
392
+ shareFallbackDays,
377
393
  targets: {
378
394
  masterCanonicalId: body.targets?.masterCanonicalId ?? 'user:master',
379
395
  masterPrivateChannelId: masterChannel,
@@ -384,6 +400,28 @@ export function registerRoutes(ctx, deps) {
384
400
  return send(200, { ok: true, savedAt: clock.now() });
385
401
  }
386
402
 
403
+ // 熟人传话:白名单 + 每天上限(默认关)
404
+ if (method === 'POST' && path === '/relay/config') {
405
+ if (!sameOrigin(req)) return send(403, { ok: false, error: 'forbidden' });
406
+ const body = JSON.parse(await readBody(req, logger) || '{}');
407
+ const list = Array.isArray(body.allowList) ? body.allowList : [];
408
+ // 只收 qq:/bili:/douyin: + 数字:昵称不参与授权(同名可冒充),写错了当场报错而不是静默失效
409
+ const bad = list.filter((x) => typeof x !== 'string' || !/^(qq|bili|douyin):\d+$/.test(x.trim()));
410
+ if (bad.length > 0) {
411
+ return send(200, { ok: false, error: `白名单里这些不是平台 uid(要 qq:数字 / bili:数字 / douyin:数字):${bad.slice(0, 3).join('、')}` });
412
+ }
413
+ const rawPerDay = Number(body.perDay ?? 5);
414
+ const perDay = Number.isFinite(rawPerDay) ? Math.min(50, Math.max(1, Math.floor(rawPerDay))) : 5;
415
+ saveConfig({
416
+ relay: {
417
+ enabled: body.enabled === true,
418
+ allowList: [...new Set(list.map((x) => x.trim()))],
419
+ perDay
420
+ }
421
+ });
422
+ return send(200, { ok: true, savedAt: clock.now() });
423
+ }
424
+
387
425
  // ── 契约 7:记忆与人物检视 ──
388
426
  if (method === 'GET' && path === '/inspector/overview') {
389
427
  const ownerFilter = url.searchParams.get('ownerId');
@@ -12,11 +12,26 @@
12
12
  * 等于覆盖开发目录,拒绝是对的,面板继续给「复制更新命令」。
13
13
  */
14
14
 
15
- /** @param {object} ctx @returns {object | null} */
15
+ /**
16
+ * 找宿主的插件管理服务。
17
+ *
18
+ * ⚠️ **两条路都得试**:cordis 的服务既能通过 `ctx.get(name)` 拿到,也能作为属性挂在 ctx 上。
19
+ * 仓库里其他服务都走 `service(ctx, name)`(先 get 再取属性),只做属性访问的话
20
+ * 一键更新会永远拿不到服务 ⇒ `canApply: false` ⇒ 面板上根本不渲染「更新到」按钮。
21
+ *
22
+ * @param {object} ctx
23
+ * @returns {object | null}
24
+ */
16
25
  export function pluginManagerOf(ctx) {
26
+ const has = (v) => v && typeof v.updateBundle === 'function' ? v : null;
27
+ try {
28
+ if (typeof ctx?.get === 'function') {
29
+ const v = has(ctx.get('plugin-manager'));
30
+ if (v !== null) return v;
31
+ }
32
+ } catch { /* 往下走属性那条 */ }
17
33
  try {
18
- const v = ctx?.['plugin-manager'];
19
- return v && typeof v.updateBundle === 'function' ? v : null;
34
+ return has(ctx?.['plugin-manager']);
20
35
  } catch {
21
36
  return null;
22
37
  }
@@ -9,8 +9,10 @@
9
9
  * - 只检查、不自动安装:装插件要动宿主的 profile,交给主人用设置页给的命令去装。
10
10
  * - 只发 GET,不带任何本机信息。
11
11
  */
12
- import { readFileSync } from 'node:fs';
13
- import { getKv, setKv } from './db.js';
12
+ import { readFileSync, realpathSync } from 'node:fs';
13
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { dshHome, getKv, setKv } from './db.js';
14
16
 
15
17
  export const PACKAGE_NAME = 'dsh-fish-soul';
16
18
  export const REPO = 'Britneycode/dsh-fish-soul';
@@ -19,6 +21,8 @@ const GH_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
19
21
  const FIRST_DELAY_MS = 30_000;
20
22
  const INTERVAL_MS = 12 * 3600_000;
21
23
  const TIMEOUT_MS = 8000;
24
+ // 面板上的「上次检查结果」超过这个时长就算旧(会误导人),进程刚启动时补查一次。
25
+ const STALE_MS = 3600_000;
22
26
  const KV_KEY = 'update.last';
23
27
 
24
28
  let cachedVersion = null;
@@ -37,6 +41,54 @@ export function pluginVersion() {
37
41
  return cachedVersion;
38
42
  }
39
43
 
44
+ /**
45
+ /**
46
+ * 这个插件是怎么装的:
47
+ * 'dev' —— 开发目录软链(link)。宿主 profile 里 `node_modules/dsh-fish-soul`
48
+ * 是个指向开发仓的符号链接。**npm 上的新版本不会覆盖它**
49
+ * (覆盖 = 把主人正在改的代码冲掉),所以一键更新在这台机器上不存在 ——
50
+ * 宿主会明确拒绝,面板要提前说清楚,不能让人以为「点了没反应」。
51
+ * 'registry' —— 宿主自己装的(npm / pnpm),落在 DSH 的目录下面,一键更新才有意义。
52
+ *
53
+ * ⚠️ 判据不能用「路径里有没有 node_modules」:主人把开发仓 clone 进某个项目的
54
+ * `node_modules/` 里开发时,那条路径也含 node_modules ⇒ 会被误判成 registry ⇒
55
+ * 面板对 dev 装的用户说「已是最���」,症状原样复发。
56
+ * 「在不在 DSH 目录里」才是真的分界:宿主装的必然在 `~/.dsh/profiles/<profile>/node_modules/…`,
57
+ * 开发仓在别处。pnpm 的虚拟 store(`.pnpm/xxx/node_modules/…`)也在 profiles 下 ⇒ 判成 registry,对。
58
+ *
59
+ * @param {string} dir 插件自己的真实目录
60
+ * @param {string} home DSH 的 home(`~/.dsh`)
61
+ * @returns {'dev'|'registry'|'unknown'}
62
+ */
63
+ export function modeFromPath(dir, home) {
64
+ try {
65
+ const rel = relative(resolve(home), resolve(dir));
66
+ // 在 home 之下(rel 不是以 .. 开头、也不是绝对路径)⇒ 宿主装的
67
+ if (rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)) return 'registry';
68
+ if (rel === '') return 'unknown'; // 就是 home 本身,判断不了
69
+ return 'dev';
70
+ } catch {
71
+ return 'unknown';
72
+ }
73
+ }
74
+
75
+ /**
76
+ * @returns {{mode: 'dev'|'registry'|'unknown', path: string}}
77
+ */
78
+ export function installInfo() {
79
+ try {
80
+ const self = realpathSync(fileURLToPath(new URL('../package.json', import.meta.url)));
81
+ const dir = dirname(self);
82
+ return { mode: modeFromPath(dir, dshHome()), path: dir };
83
+ } catch {
84
+ return { mode: 'unknown', path: '' };
85
+ }
86
+ }
87
+
88
+ export function installMode() {
89
+ return installInfo().mode;
90
+ }
91
+
40
92
  /** "v1.2.3-rc.1" → { nums:[1,2,3], pre:['rc',1] };看不懂返回 null。 */
41
93
  function parse(v) {
42
94
  const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v ?? '').trim());
@@ -88,6 +140,9 @@ export class UpdateChecker {
88
140
  this.random = random ?? Math.random;
89
141
  this.timer = null;
90
142
  this.running = null;
143
+ // 「本进程还没查过」—— 放构造函数而不是 start():
144
+ // start(); stop(); start()(插件热重载)不该把它又置回 true 而多问一次。
145
+ this.freshProcess = true;
91
146
  }
92
147
 
93
148
  autoCheck() {
@@ -105,11 +160,33 @@ export class UpdateChecker {
105
160
  return Math.max(FIRST_DELAY_MS, Math.min(jitter, last + jitter - this.now()));
106
161
  }
107
162
 
163
+ /**
164
+ * 上次查到的结果是不是已经旧到会误导人(超过 STALE_MS)。
165
+ * 从没查过 ⇒ 算旧(要查)。
166
+ */
167
+ staleResult() {
168
+ const last = getKv(this.db, KV_KEY, null)?.checkedAt;
169
+ return typeof last !== 'number' || (this.now() - last) > STALE_MS;
170
+ }
171
+
108
172
  start() {
109
173
  this.stop();
110
174
  this.stopped = false;
175
+ // 🔴 **进程刚启动、且上次的结果已经旧到会误导人时,补查一次**(30 秒后)。
176
+ // 以前 nextDelay() 只看 kv 里的 checkedAt ⇒ 宿主重启后可能要再等好几个小时
177
+ // 才重查,面板于是显示着**上一次**的结果(这次就显示 latest=0.18.5,
178
+ // 而 npm 上早就是 0.18.7 了)—— 「已是最新」是假的,主人根本不知道出了新版。
179
+ //
180
+ // ⚠️ 但**不能每次启动都问**:GitHub 未认证 API 是 60 次/小时/IP,
181
+ // 崩溃重启循环会直接吃满;而且 nextDelay() 的文档写着
182
+ // 「重启频繁时也不会每次启动都去问」—— 那是一条被代码主动推翻的承诺。
183
+ // 所以加了 STALE_MS 门槛:结果超过 1 小时才算「旧到会误导人」。
111
184
  const tick = async () => {
112
- try { if (this.autoCheck()) await this.check(); }
185
+ try {
186
+ // 自动检查开着才真的查。查过了才把「本进程已问过」记上 ——
187
+ // 否则自动检查关着时,那 30 秒的机会会被白白烧掉,之后又是十几个小时不查。
188
+ if (this.autoCheck()) { await this.check(); this.freshProcess = false; }
189
+ }
113
190
  catch (e) { this.log('warn', `[fish-soul] 检查更新出错:${e instanceof Error ? e.message : e}`); }
114
191
  if (!this.stopped) {
115
192
  try { arm(); }
@@ -118,8 +195,9 @@ export class UpdateChecker {
118
195
  };
119
196
  const arm = () => {
120
197
  let delay;
121
- try { delay = this.nextDelay(); }
122
- catch (e) {
198
+ try {
199
+ delay = (this.freshProcess && this.staleResult()) ? FIRST_DELAY_MS : this.nextDelay();
200
+ } catch (e) {
123
201
  this.log('warn', `[fish-soul] 读取更新检查间隔失败,按默认间隔重试:${e instanceof Error ? e.message : e}`);
124
202
  delay = INTERVAL_MS;
125
203
  }
@@ -185,6 +263,7 @@ export class UpdateChecker {
185
263
  }
186
264
 
187
265
  state() {
266
+ const info = installInfo(); // 一次取值就够(realpathSync 是同步的,面板每 60 秒轮询一次)
188
267
  const last = getKv(this.db, KV_KEY, null);
189
268
  const latest = last?.latest ?? null;
190
269
  const hasUpdate = latest !== null && compareVersions(latest, this.current) > 0;
@@ -201,7 +280,11 @@ export class UpdateChecker {
201
280
  publishedAt: last?.publishedAt ?? null,
202
281
  error: last?.error ?? '',
203
282
  autoCheck: this.autoCheck(),
204
- command: hasUpdate ? updateCommand(latest) : ''
283
+ command: hasUpdate ? updateCommand(latest) : '',
284
+ // dev(link)安装:npm 版不会覆盖开发目录 ⇒ 一键更新在这台机器上不存在。
285
+ // 带上真实路径:面板给的更新命令要用它,不能给占位符(复制过去直接报错)。
286
+ installMode: info.mode,
287
+ installPath: info.path
205
288
  };
206
289
  }
207
290
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-soul",
3
- "version": "0.18.6",
3
+ "version": "0.18.8",
4
4
  "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.15.37)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -64,6 +64,6 @@
64
64
  }
65
65
  },
66
66
  "scripts": {
67
- "test": "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-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.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-post-jobs.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/smoke.mjs && node test/douyin-browser.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/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/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.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/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/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.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/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/relay-other-platform.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/memory-source-label.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-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs"
67
+ "test": "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-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.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-post-jobs.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/smoke.mjs && node test/douyin-browser.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/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/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.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/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/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.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/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/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-config-route.mjs && node test/share-fallback.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/memory-source-label.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-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs"
68
68
  }
69
69
  }