dsh-fish-soul 0.16.6 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/lib/client.js +4 -2
- package/lib/client.models.js +1 -1
- package/lib/client.soul.js +22 -9
- package/lib/config-schema.js +2 -0
- package/lib/db.js +1 -0
- package/lib/diag-log.js +1 -0
- package/lib/gateway.js +28 -7
- package/lib/importer.js +4 -3
- package/lib/index.js +14 -13
- package/lib/llm.js +14 -10
- package/lib/memory-bulk.js +4 -0
- package/lib/panel.css +8 -1
- package/lib/routes-soul.js +9 -7
- package/lib/routes-v07.js +11 -25
- package/lib/routes.js +15 -3
- package/lib/sticker-vision.js +21 -0
- package/lib/stickers.js +25 -18
- package/lib/time-util.js +7 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
|
|
4
4
|
|
|
5
|
-
DSH 插件(单角色 `feiyu`)。版本 **0.
|
|
5
|
+
DSH 插件(单角色 `feiyu`)。版本 **0.18.0**。
|
|
6
6
|
|
|
7
7
|
QQ 交流群:**1125962189**
|
|
8
8
|
|
|
@@ -57,7 +57,7 @@ dsh plugin --profile desktop add dsh-fish-soul
|
|
|
57
57
|
|
|
58
58
|
如同时安装 `dsh-cixisound`,QQ 会话在宿主支持工具护栏且一轮只有一个已识别的说话人时,可通过 `sound_read` 分析本轮录音。受限会话只放行本轮路径和 `input` 参数,不开放通用文件访问;如果设置中已明确为主人或全部聊天放开宿主工具,则保持原有工具权限,`sound_read` 也可访问其他文件。需要已安装音频分析插件,安装后已有会话可能需要重开;原件格式不受该插件支持时不能保证分析成功。
|
|
59
59
|
|
|
60
|
-
「DSH
|
|
60
|
+
「DSH 里鱼的会话生成本地语音」仅对鱼的已登记会话里直接打字、正常完成的回复中,以 `[语音]` 开头的独立段落生成 `voice-out` 本地文件,不向 QQ 发送;不在对话框内播放。沿用「说」的服务、字数和每天次数上限,未就绪或失败时文字回复不受影响,最多保留 30 个文件;本地文件可能包含私密内容。
|
|
61
61
|
|
|
62
62
|
|
|
63
63
|
| 路径 | 内容 |
|
|
@@ -184,4 +184,6 @@ MIT
|
|
|
184
184
|
|
|
185
185
|
QQ 重发队列只重试明确未送达的消息。重发过程中如果程序中断,消息会标记为**状态未知**,不会自动重发;请先在 QQ 中核实,避免重复发送。断线期间队列降低检查频率,连接恢复后会立即尝试补发。
|
|
186
186
|
|
|
187
|
-
「聊天文本存档」**默认开启**(`chatArchive.enabled`,v0.15.25 起):会话列表**留空 = 记下所有会话**;只有填了会话 ID(如 `private:123`、`group:456
|
|
187
|
+
「聊天文本存档」**默认开启**(`chatArchive.enabled`,v0.15.25 起):会话列表**留空 = 记下所有会话**;只有填了会话 ID(如 `private:123`、`group:456`)才按白名单过滤。**不想要就在设置页关掉,或按会话删**。仅保存插件实际接入的文本,包括在鱼的已绑定会话中通过 DSH 输入的文本及正常完成的回复;不包含附件、未被接入的消息或历史消息,不能保证平台聊天全量;历史请另行导入。文本单独存于未加密的本地数据库,可分会话查看或删除,默认保留 30 天、过期文本在插件运行期间清理;离线期间不会清理。缩短期限可能立即删除过期文本;用户自行制作的备份和复制件需要另行删除。
|
|
188
|
+
|
|
189
|
+
记忆内容可在编辑时设置「事件日期」,仅调整列表排序,留空恢复按创建日期排序;不会修改创建时间或改变记忆检索、周记归档日期。JSON 导出会保留此日期。
|
package/lib/client.js
CHANGED
|
@@ -504,7 +504,7 @@ window.__ModuleLoader__.load({
|
|
|
504
504
|
const [busy, setBusy] = react.useState(false);
|
|
505
505
|
const [form, setForm, patch] = useForm(data, () => ({
|
|
506
506
|
enabled: qq.enabled === true, wsUrl: qq.wsUrl ?? "ws://127.0.0.1:3001", accessToken: "", masterQqUin: data.masterQqUin ?? "",
|
|
507
|
-
groupAllowList: (qq.groupAllowList ?? []).join(", "), allGroups: qq.allGroups === true, mentionOnly: qq.mentionOnly === true, followUpCount: qq.followUpCount ?? 3, followUpSeconds: qq.followUpSeconds ?? 120, batchMs: qq.batchMs ?? 3000, replyWindowMinutes: qq.replyWindowMinutes ?? 120,
|
|
507
|
+
groupAllowList: (qq.groupAllowList ?? []).join(", "), allGroups: qq.allGroups === true, privateAllowList: (qq.privateAllowList ?? []).join(", "), allFriends: qq.allFriends === true, mentionOnly: qq.mentionOnly === true, followUpCount: qq.followUpCount ?? 3, followUpSeconds: qq.followUpSeconds ?? 120, batchMs: qq.batchMs ?? 3000, replyWindowMinutes: qq.replyWindowMinutes ?? 120,
|
|
508
508
|
callNames: (qq.callNames ?? []).join(", "), ij: { ...(qq.interject ?? {}), chance: Math.round((qq.interject?.chance ?? 0.05) * 100), keywords: (qq.interject?.keywords ?? []).join(", ") },
|
|
509
509
|
stickersPerDay: qq.stickers?.perDay ?? 10,
|
|
510
510
|
ga: { enabled: qq.groupAdmin?.enabled === true, groupId: qq.groupAdmin?.groupId ?? "", announce: qq.groupAdmin?.announce !== false, autoApprove: qq.groupAdmin?.autoApprove !== false }
|
|
@@ -516,7 +516,7 @@ window.__ModuleLoader__.load({
|
|
|
516
516
|
setForm(next);
|
|
517
517
|
const res = await api("POST", "/channels/qq-config", {
|
|
518
518
|
enabled: next.enabled, wsUrl: next.wsUrl, ...(next.accessToken !== "" ? { accessToken: next.accessToken } : {}),
|
|
519
|
-
masterQqUin: next.masterQqUin, groupAllowList: split(next.groupAllowList), allGroups: next.allGroups === true, mentionOnly: next.mentionOnly === true,
|
|
519
|
+
masterQqUin: next.masterQqUin, groupAllowList: split(next.groupAllowList), allGroups: next.allGroups === true, privateAllowList: split(next.privateAllowList), allFriends: next.allFriends === true, mentionOnly: next.mentionOnly === true,
|
|
520
520
|
followUpCount: Number(next.followUpCount), followUpSeconds: Number(next.followUpSeconds), batchMs: Number(next.batchMs), replyWindowMinutes: Number(next.replyWindowMinutes), callNames: split(next.callNames),
|
|
521
521
|
interject: { enabled: next.ij.enabled === true, chance: Number(next.ij.chance) / 100, cooldownMinutes: Number(next.ij.cooldownMinutes), maxPerHour: Number(next.ij.maxPerHour), keywords: split(next.ij.keywords) },
|
|
522
522
|
groupAdmin: { enabled: next.ga.enabled === true, groupId: next.ga.groupId, announce: next.ga.announce === true, autoApprove: next.ga.autoApprove === true }
|
|
@@ -549,6 +549,8 @@ window.__ModuleLoader__.load({
|
|
|
549
549
|
form.enabled ? Row({ title: "主人 QQ" }, field("masterQqUin", { inputMode: "numeric" })) : null,
|
|
550
550
|
form.enabled ? Row({ title: "所有群" }, h(Switch, { label: "所有群", checked: form.allGroups, onChange: (v) => save({ allGroups: v }) }), Muted(form.allGroups ? "任何群里 @ 都回" : "只回下面列的群")) : null,
|
|
551
551
|
form.enabled && !form.allGroups ? Row({ title: "只在这些群" }, field("groupAllowList", { placeholder: "群号,逗号分隔;空 = 谁都不回" })) : null,
|
|
552
|
+
form.enabled ? Row({ title: "所有好友", desc: "关掉后只回下面名单里的人,主人始终回。升级前好友私聊都会回,想保持那样就打开" }, h(Switch, { label: "所有好友", checked: form.allFriends === true, onChange: (v) => save({ allFriends: v }) }), Muted(form.allFriends ? "任何好友的私聊都回" : "只回名单里的人")) : null,
|
|
553
|
+
form.enabled && !form.allFriends ? Row({ title: "只回这些人" }, field("privateAllowList", { placeholder: "QQ 号,逗号分隔;空 = 只回主人" })) : null,
|
|
552
554
|
form.enabled ? Row({ title: "群里只回点名", desc: "打开后:只在她被 @ 或叫名字时开口,关掉「接着听」和「自己想插一句」。几个机器人待在同一个群、互相接话刷屏时打开它" },
|
|
553
555
|
h(Switch, { label: "群里只回点名", checked: form.mentionOnly === true, onChange: (v) => save({ mentionOnly: v }) })) : null,
|
|
554
556
|
form.enabled && !form.mentionOnly ? Row({ title: "点名后接着听" },
|
package/lib/client.models.js
CHANGED
|
@@ -211,7 +211,7 @@ window.__ModuleLoader__.load({
|
|
|
211
211
|
on ? Group({ title: "语音文件" },
|
|
212
212
|
Row({ title: "保存收到的 QQ 语音", desc: `仅保存需回复的好友私聊和明确白名单群语音,最多 30 条;未加密。目录:${v.incomingDir}。受限会话的 sound_read 仅能分析本轮单一说话人文件;已放开工具的会话保留原有权限。安装插件后可能需要重开会话。` }, h(Switch, { label: "保存收到的 QQ 语音", checked: v.saveIncoming === true, onChange: setIncoming })),
|
|
213
213
|
Row({ title: "清理 QQ 语音", desc: v.filesError || `当前 ${v.incomingCount ?? 0} 条;不删除备份或复制件` }, Button({ onClick: clearIncoming }, "清空")),
|
|
214
|
-
Row({ title: "DSH 里鱼的会话生成本地语音", desc:
|
|
214
|
+
Row({ title: "DSH 里鱼的会话生成本地语音", desc: `仅将独立的 [语音] 段生成文件,使用「说」的服务与配额;不会发送 QQ。超字数或失败保留文字。最多保留 30 条,目录:${v.desktopDir}${v.desktopLatest ? `;最近:${v.desktopLatest}` : ""}` }, h(Switch, { label: "DSH 里鱼的会话生成本地语音", checked: v.desktopTts === true, onChange: (x) => save({ desktopTts: x }) }))) : null,
|
|
215
215
|
on ? Group({ title: "听(语音转文字)", aside: sideState(stt, v.sttLeft) },
|
|
216
216
|
Row({ title: "服务商", desc: "百炼和 MiniMax 的端点跟 OpenAI 不一样,选错了会一直「听不到」" }, h(Seg, { label: "听的服务商", value: form.sttProvider, options: STT_PROVIDERS, onChange: (x) => { patch({ sttProvider: x }); save({ sttProvider: x }); } })),
|
|
217
217
|
Row({ title: "接口地址", desc: sttDash ? "阿里百炼填 https://dashscope.aliyuncs.com/compatible-mode/v1" : sttMini ? "MiniMax 填 https://api.minimax.cn/v1" : "" }, field("sttBaseURL", { placeholder: stt.effectiveBaseURL || "https://api.siliconflow.cn/v1", "aria-label": "听的接口地址" })),
|
package/lib/client.soul.js
CHANGED
|
@@ -34,7 +34,7 @@ window.__ModuleLoader__.load({
|
|
|
34
34
|
|
|
35
35
|
// ── 一条记忆:点笔改,改内容 = 新写一条、旧的留档 ──
|
|
36
36
|
function MemoryItem({ m, ui, api, notify, refresh, curGen, selectable, selected, onSelect }) {
|
|
37
|
-
const { h, Tag, Dot, IconButton, Area, Num, Select, Button } = ui;
|
|
37
|
+
const { h, Tag, Dot, IconButton, Input, Area, Num, Select, Button } = ui;
|
|
38
38
|
const [edit, setEdit] = react.useState(null);
|
|
39
39
|
const [sources, setSources] = react.useState(null);
|
|
40
40
|
const imp = m.importance ?? 1;
|
|
@@ -50,7 +50,7 @@ window.__ModuleLoader__.load({
|
|
|
50
50
|
}
|
|
51
51
|
async function save() {
|
|
52
52
|
const importanceChanged = Number(edit.importance) !== (m.importance ?? 1);
|
|
53
|
-
const r = await api("POST", "/inspector/memory-edit", { id: m.id, content: edit.content, kind: edit.kind, ...(importanceChanged ? { importance: Number(edit.importance) } : {}) });
|
|
53
|
+
const r = await api("POST", "/inspector/memory-edit", { id: m.id, content: edit.content, kind: edit.kind, sortDate: edit.sortDate || null, ...(importanceChanged ? { importance: Number(edit.importance) } : {}) });
|
|
54
54
|
if (r?.ok) { setEdit(null); notify(r.replaced ? "已改(旧的留档了)" : "已保存"); refresh(); } else notify(r?.error ?? "保存失败");
|
|
55
55
|
}
|
|
56
56
|
if (edit !== null) {
|
|
@@ -59,6 +59,8 @@ window.__ModuleLoader__.load({
|
|
|
59
59
|
h("div", { className: "fs-ctl" },
|
|
60
60
|
Select({ value: edit.kind, "aria-label": "类型", onChange: (e) => setEdit({ ...edit, kind: e.target.value }) },
|
|
61
61
|
...Object.entries(KIND).filter(([k]) => k !== "weekly" && k !== "diary").map(([k, v]) => h("option", { key: k, value: k }, v))),
|
|
62
|
+
h("span", { className: "fs-unit" }, "事件日期"),
|
|
63
|
+
Input({ type: "date", value: edit.sortDate, "aria-label": "事件日期(留空按创建日期排序)", onChange: (e) => setEdit({ ...edit, sortDate: e.target.value }) }),
|
|
62
64
|
h("span", { className: "fs-unit" }, "重要度"),
|
|
63
65
|
Num({ min: 1, max: 5, value: edit.importance, "aria-label": "重要度", onChange: (e) => setEdit({ ...edit, importance: e.target.value }) }),
|
|
64
66
|
h("span", { className: "fs-fill-gap" }),
|
|
@@ -76,9 +78,10 @@ window.__ModuleLoader__.load({
|
|
|
76
78
|
m.visibility === "private" ? Tag("私密", "warning", { title: "私聊里说的,群里不会提" }) : null,
|
|
77
79
|
m.about ? Tag(`关于 ${m.aboutName ?? m.about.replace(/^user:/, "")}`, "outline") : null,
|
|
78
80
|
imp >= 2 ? h("span", { title: imp >= 3 ? "不会淡忘" : undefined }, "★".repeat(imp)) : null,
|
|
81
|
+
m.sortDate ? h("span", { title: "事件日期,仅用于列表排序" }, m.sortDate) : null,
|
|
79
82
|
h("span", { title: origin }, m.source ?? ""),
|
|
80
83
|
h("span", { title: vec[1], style: { display: "inline-flex" } }, Dot(vec[0])),
|
|
81
|
-
m.kind === "weekly" ? Button({ variant: "ghost", onClick: async () => { if (sources) { setSources(null); return; } const r = await api("GET", `/memory/weekly/sources?summaryId=${m.id}`); if (r?.ok) setSources(r.sources); else notify(r?.error ?? "来源读取失败"); } }, sources ? "收起来源" : "查看来源") : IconButton("edit", "修改", () => setEdit({ content: m.content, importance: imp, kind: m.kind })),
|
|
84
|
+
m.kind === "weekly" ? Button({ variant: "ghost", onClick: async () => { if (sources) { setSources(null); return; } const r = await api("GET", `/memory/weekly/sources?summaryId=${m.id}`); if (r?.ok) setSources(r.sources); else notify(r?.error ?? "来源读取失败"); } }, sources ? "收起来源" : "查看来源") : IconButton("edit", "修改", () => setEdit({ content: m.content, importance: imp, kind: m.kind, sortDate: m.sortDate ?? "" })),
|
|
82
85
|
IconButton("close", "删除", forget))),
|
|
83
86
|
sources ? h("div", { className: "fs-item-sub" }, ...sources.map((x) => h("div", { key: x.id }, `#${x.id} · ${x.content}`))) : null);
|
|
84
87
|
}
|
|
@@ -442,7 +445,7 @@ window.__ModuleLoader__.load({
|
|
|
442
445
|
async function saveChat() {
|
|
443
446
|
const channels=form.channels.split(/[,,\n]/).map(x=>x.trim()).filter(Boolean);
|
|
444
447
|
if(Number(form.days)<chat.days && !(await confirm({ title: "缩短保留期限", description: "会立即清理已过期的本地聊天文本,备份和复制件不会同步清理。继续?", danger: true })))return;
|
|
445
|
-
if(form.enabled && !(await confirm({ title: "启用聊天文本存档", description: "
|
|
448
|
+
if(form.enabled && !(await confirm({ title: "启用聊天文本存档", description: "保存选定会话中插件接入的聊天文本(包括在鱼会话的 DSH 窗口里输入和完成的回复),可能包含私密内容;文件未加密。附件和未接入的消息不会保存,历史消息无法补录。继续?" })))return;
|
|
446
449
|
const r=await api("POST", "/chat-archive/config", {enabled:form.enabled,channels,days:Number(form.days)});
|
|
447
450
|
if(r?.ok){setForm({enabled:r.enabled,channels:r.channels.join(", "),days:r.days});setItems(null);await loadChat();notify("聊天存档设置已保存");}else notify(r?.error??"保存失败");
|
|
448
451
|
}
|
|
@@ -464,8 +467,8 @@ window.__ModuleLoader__.load({
|
|
|
464
467
|
storage.files.length>5 ? Button({variant:"ghost",onClick:()=>setShowAllFiles(!showAllFiles)},showAllFiles ? "收起存档" : `显示全部 ${storage.files.length} 份`) : null,
|
|
465
468
|
Row({title:"全部记忆记录",meta:"包括已归档和失效记录",stack:true},Input({className:"wide",value:historyQuery,placeholder:"搜索记忆", "aria-label":"搜索全部记忆",onChange:e=>setHistoryQuery(e.target.value)}),Button({onClick:()=>searchHistory(null)},"搜索")),
|
|
466
469
|
history?h("div",{className:"fs-list"},...history.rows.map(x=>h("div",{className:"fs-row",key:x.id},h("span",{style:{overflowWrap:"anywhere"}},`#${x.id} · ${{active:"当前",archived:"已归档",outdated:"过时",superseded:"已替换"}[x.status] ?? x.status} · ${x.visibility === "private" ? "私密 · " : ""}${x.content}`))),history.next?Button({onClick:()=>searchHistory(history.next)},"加载更早"):null):null),
|
|
467
|
-
Group({title:"聊天文本存档",tip:"
|
|
468
|
-
Row({title:"启用",meta:"
|
|
470
|
+
Group({title:"聊天文本存档",tip:"保存选定会话中插件接入的文本,包括鱼会话的 DSH 对话;不包括附件或全部平台消息"},
|
|
471
|
+
Row({title:"启用",meta:"包括鱼会话在 DSH 里的输入及正常完成的回复。存在本机(文件权限仅本人可读,内容未加密),只从开启后记录、历史不补录;不想要随时关掉或删掉"},h(Switch,{label:"聊天文本存档",checked:form.enabled,onChange:v=>setForm({...form,enabled:v})})),
|
|
469
472
|
Row({title:"只记这些会话",meta:"留空 = 所有会话都记(推荐);填了就只记这些,多个 ID 用逗号分隔,例如 private:123、group:456",stack:true},Input({className:"wide",value:form.channels,"aria-label":"聊天存档会话 ID",onChange:e=>setForm({...form,channels:e.target.value})})),
|
|
470
473
|
Row({title:"保留天数",meta:"过期文本按天清理;备份和复制件需另行清理"},Num({min:1,max:3650,value:form.days,"aria-label":"聊天存档保留天数",onChange:e=>setForm({...form,days:e.target.value})}),Button({onClick:saveChat},"保存")),
|
|
471
474
|
Row({title:"已保存文本"},Muted(`${chat.count} 条`)),
|
|
@@ -484,15 +487,18 @@ window.__ModuleLoader__.load({
|
|
|
484
487
|
const [source, setSource] = react.useState("");
|
|
485
488
|
const [bulk, setBulk] = react.useState(false);
|
|
486
489
|
const [sel, setSel] = react.useState(() => new Set());
|
|
490
|
+
const [page, setPage] = react.useState(0);
|
|
491
|
+
const [dateValue, setDateValue] = react.useState("");
|
|
487
492
|
const [confirm, confirmNode] = useConfirm();
|
|
488
|
-
const
|
|
493
|
+
const pageSize = bulk ? 100 : 100;
|
|
494
|
+
const qs = new URLSearchParams({ ...(owner !== "all" ? { ownerId: owner } : {}), ...(qApplied ? { q: qApplied } : {}), ...(source ? { source } : {}), limit: String(pageSize), offset: String(page * pageSize) }).toString();
|
|
489
495
|
const [data, load] = usePoll(api, `/inspector/overview${qs ? `?${qs}` : ""}`, 0);
|
|
490
496
|
async function dropPending(id) {
|
|
491
497
|
const r = await api("POST", "/inspector/forget", { targetType: "pending", id });
|
|
492
498
|
if (r?.ok) { notify("已删掉这条待办"); load(); } else notify(r?.error ?? "删除失败");
|
|
493
499
|
}
|
|
494
500
|
const [adding, setAdding] = react.useState("");
|
|
495
|
-
react.useEffect(() => { setSel(new Set()); }, [owner, qApplied, source, bulk]);
|
|
501
|
+
react.useEffect(() => { setSel(new Set()); setPage(0); }, [owner, qApplied, source, bulk]);
|
|
496
502
|
if (!data) return null;
|
|
497
503
|
const persons = data.persons ?? [];
|
|
498
504
|
const memories = data.memories ?? [];
|
|
@@ -522,6 +528,9 @@ window.__ModuleLoader__.load({
|
|
|
522
528
|
Button({ variant: "ghost", disabled: n === 0, onClick: () => runBulk("visibility", "private", "标成私密") }, "标私密"),
|
|
523
529
|
Button({ variant: "ghost", disabled: n === 0, onClick: () => runBulk("visibility", "normal", "取消私密") }, "取消私密"),
|
|
524
530
|
...[1, 3, 5].map((v) => Button({ key: v, variant: "ghost", disabled: n === 0, onClick: () => runBulk("importance", v, `重要度改成 ${v}`) }, `重要度 ${v}`)),
|
|
531
|
+
Input({ type: "date", value: dateValue, "aria-label": "批量事件日期", onChange: (e) => setDateValue(e.target.value) }),
|
|
532
|
+
Button({ variant: "ghost", disabled: n === 0 || dateValue === "", onClick: () => runBulk("sortDate", dateValue, "事件日期已改") }, "设日期"),
|
|
533
|
+
Button({ variant: "ghost", disabled: n === 0, onClick: () => runBulk("sortDate", null, "事件日期已清空") }, "清日期"),
|
|
525
534
|
h("span", { className: "fs-fill-gap" }),
|
|
526
535
|
Button({ variant: "ghost", disabled: !narrowed, title: narrowed ? "删掉符合当前筛选(人 / 来源 / 包含的字)的全部记忆,不只是这页显示的" : "先选一个人、来源或输入要包含的字", onClick: () => runBulk("forget", null, "按筛选删除", true) },
|
|
527
536
|
`删掉符合筛选的全部${data.matchedTotal != null ? ` ${data.matchedTotal} 条` : ""}`)));
|
|
@@ -554,7 +563,11 @@ window.__ModuleLoader__.load({
|
|
|
554
563
|
Input({ value: adding, className: "wide", placeholder: "手动记一条(比如:她不吃香菜)", onChange: (e) => setAdding(e.target.value), onKeyDown: (e) => { if (e.key === "Enter" && adding.trim()) add(); } }),
|
|
555
564
|
Button({ disabled: adding.trim() === "", onClick: add }, "记下")) : null,
|
|
556
565
|
h("div", { className: "fs-list" }, memories.length === 0 ? Empty("还没有记忆")
|
|
557
|
-
: memories.map((m) => h(MemoryItem, { key: m.id, m, ui, api, notify, refresh: load, curGen: data.currentGenerationId ?? 1, selectable: bulk, selected: sel.has(m.id), onSelect })))
|
|
566
|
+
: memories.map((m) => h(MemoryItem, { key: m.id, m, ui, api, notify, refresh: load, curGen: data.currentGenerationId ?? 1, selectable: bulk, selected: sel.has(m.id), onSelect }))),
|
|
567
|
+
data.matchedTotal > pageSize ? h("div", { className: "fs-row" },
|
|
568
|
+
Button({ variant: "ghost", disabled: page === 0, onClick: () => setPage(page - 1) }, "上一页"),
|
|
569
|
+
Muted(`第 ${page + 1} / ${Math.ceil(data.matchedTotal / pageSize)} 页`),
|
|
570
|
+
Button({ variant: "ghost", disabled: (page + 1) * pageSize >= data.matchedTotal, onClick: () => setPage(page + 1) }, "下一页")) : null),
|
|
558
571
|
pendings.length === 0 ? null : Group({ title: "待办", aside: Tag(String(pendings.length), "outline") },
|
|
559
572
|
h("div", { className: "fs-list" }, pendings.map((p) => Item({
|
|
560
573
|
key: p.id, lead: Muted(props.fmtDueAt(p.dueAt), { className: "fs-unit num" }), text: p.reason,
|
package/lib/config-schema.js
CHANGED
|
@@ -11,6 +11,8 @@ export function fishSoulConfigSchema(z) {
|
|
|
11
11
|
accessToken: z.string().default(''),
|
|
12
12
|
groupAllowList: z.array(z.string()).default([]), // 白名单:空 = 谁都不放行(默认拒绝);群要在这里列出才会被回应
|
|
13
13
|
allGroups: z.boolean().default(false), // 显式放开:true = 所有群(仍然只听点名)
|
|
14
|
+
privateAllowList: z.array(z.string()).default([]), // 私聊白名单:空 = 谁都不放行(默认拒绝,主人永远放行);要放开所有好友见 allFriends
|
|
15
|
+
allFriends: z.boolean().default(false), // 显式放开:true = 所有好友的私聊都回(等价于旧的默认行为)
|
|
14
16
|
followUpCount: z.number().default(3),
|
|
15
17
|
followUpSeconds: z.number().default(120),
|
|
16
18
|
followUpSmart: z.boolean().default(false), // #59 她自己说"这轮聊完了"就不接着听(默认关)
|
package/lib/db.js
CHANGED
|
@@ -205,6 +205,7 @@ const MIGRATIONS = [
|
|
|
205
205
|
'ALTER TABLE memory ADD COLUMN last_recalled_at INTEGER',
|
|
206
206
|
"ALTER TABLE memory ADD COLUMN importance_locked INTEGER NOT NULL DEFAULT 0",
|
|
207
207
|
"ALTER TABLE memory ADD COLUMN importance_auto_recalled INTEGER NOT NULL DEFAULT 0",
|
|
208
|
+
'ALTER TABLE memory ADD COLUMN sort_date TEXT',
|
|
208
209
|
'CREATE INDEX IF NOT EXISTS idx_memory_about ON memory(character_id, about, status)',
|
|
209
210
|
'CREATE INDEX IF NOT EXISTS idx_memory_superseded_by ON memory(superseded_by) WHERE superseded_by IS NOT NULL',
|
|
210
211
|
// v0.8:好感度、上次结算时间、上一次来聊的时间(隔了 1 小时以上才算新的一次)、主人手动定的阶段不自动改
|
package/lib/diag-log.js
CHANGED
package/lib/gateway.js
CHANGED
|
@@ -225,6 +225,8 @@ export class ChatGateway {
|
|
|
225
225
|
enabled: q.enabled === true,
|
|
226
226
|
groupAllowList: Array.isArray(q.groupAllowList) ? q.groupAllowList.map(String) : [],
|
|
227
227
|
allGroups: q.allGroups === true,
|
|
228
|
+
privateAllowList: Array.isArray(q.privateAllowList) ? q.privateAllowList.map((v) => String(v).trim()).filter(Boolean) : [],
|
|
229
|
+
allFriends: q.allFriends === true, // 私聊白名单配套开关:true = 所有好友都回(旧默认行为)
|
|
228
230
|
followUpCount: Number.isFinite(Number(q.followUpCount)) ? Number(q.followUpCount) : 3,
|
|
229
231
|
followUpSeconds: Number.isFinite(Number(q.followUpSeconds)) ? Number(q.followUpSeconds) : 120,
|
|
230
232
|
followUpSmart: q.followUpSmart === true, // #59 她说"这轮聊完了"就不接着听(默认关)
|
|
@@ -1110,8 +1112,18 @@ export class ChatGateway {
|
|
|
1110
1112
|
let interject = false;
|
|
1111
1113
|
if (m.chatType === 'private') {
|
|
1112
1114
|
const friend = m.subType === 'friend' || this.channel.isFriend(m.userId) || m.userId === this.masterQq();
|
|
1113
|
-
|
|
1115
|
+
/**
|
|
1116
|
+
* 私聊白名单(`qq.privateAllowList` / `qq.allFriends`)。
|
|
1117
|
+
*
|
|
1118
|
+
* 为什么要这个开关:群的准入靠 `groupAllowList` 管,私聊这一支原来只判「是不是好友」,
|
|
1119
|
+
* 好友申请一通过就等于放进来一个能一直触发她的人,没有任何按人收口的地方。
|
|
1120
|
+
* 语义跟群对齐:名单空 = 谁都不放行(主人永远放行),要放开所有好友得显式开 `qq.allFriends`
|
|
1121
|
+
* (等价于旧的默认行为,升级的人照着打开即可)。被挡下的照存记忆,日志能看出被挡的是谁。
|
|
1122
|
+
*/
|
|
1123
|
+
const listed = cfg.allFriends === true || (cfg.privateAllowList ?? []).includes(String(m.userId)) || String(m.userId) === this.masterQq();
|
|
1124
|
+
decision = friend && listed ? 'reply' : 'memorize';
|
|
1114
1125
|
if (!friend) reason = '不是好友';
|
|
1126
|
+
else if (!listed) reason = '不在私聊白名单';
|
|
1115
1127
|
} else {
|
|
1116
1128
|
const called = !m.mentioned && this.callNames(cfg).some((n) => m.text.includes(n));
|
|
1117
1129
|
/**
|
|
@@ -1731,6 +1743,10 @@ export class ChatGateway {
|
|
|
1731
1743
|
if (st.fromUs) this.note('failed', { channelId: st.channelId ?? this.bound.get(sessionId)?.channel_id ?? '', reason: `这一轮没正常结束(${d.reason?.kind ?? '未知'})` });
|
|
1732
1744
|
// #78:DSH 桌面端打字的轮次不外发,但**要记动态** —— 以前在 DSH 里聊,动态页整片空白。
|
|
1733
1745
|
if (st.dshTyped === true) {
|
|
1746
|
+
if (completed && st.text && this.bound.get(sessionId)?.channel_id) {
|
|
1747
|
+
try { this.soul.archiveDesktop?.(this.bound.get(sessionId).channel_id, st.text); }
|
|
1748
|
+
catch { this.log('warn', '[fish-soul] DSH 回复存档失败,聊天继续'); }
|
|
1749
|
+
}
|
|
1734
1750
|
if (completed && this.getConfig?.()?.voice?.desktopTts === true && this.voice?.readyFor('tts')) void this.saveDesktopVoice(st.text);
|
|
1735
1751
|
const recall = this.soul.recallInfo?.(sessionId, st) ?? { memories: [], at: 0, unknown: false };
|
|
1736
1752
|
this.note('dsh', {
|
|
@@ -1756,14 +1772,19 @@ export class ChatGateway {
|
|
|
1756
1772
|
}
|
|
1757
1773
|
}
|
|
1758
1774
|
|
|
1759
|
-
/** DSH
|
|
1775
|
+
/** DSH 内只合成独立的 [语音] 段,不经 QQ 出站。 */
|
|
1760
1776
|
async saveDesktopVoice(text) {
|
|
1761
1777
|
try {
|
|
1762
|
-
const
|
|
1763
|
-
if (!
|
|
1764
|
-
const
|
|
1765
|
-
|
|
1766
|
-
|
|
1778
|
+
const raw = String(text ?? '').trim();
|
|
1779
|
+
if (!raw || SILENT_RE.test(raw)) return;
|
|
1780
|
+
for (const p of raw.split(/\n{2,}/)) {
|
|
1781
|
+
if (!VOICE_RE.test(p)) continue;
|
|
1782
|
+
const plain = 抠正文图(p.replace(VOICE_RE, '')).净文字.trim();
|
|
1783
|
+
if (!plain || this.getConfig?.()?.voice?.desktopTts !== true || this.getConfig?.()?.voice?.enabled !== true) continue;
|
|
1784
|
+
const bytes = await this.voice.synthesize(plain);
|
|
1785
|
+
if (bytes && this.getConfig?.()?.voice?.desktopTts === true && this.getConfig?.()?.voice?.enabled === true) saveVoiceFile('out', bytes);
|
|
1786
|
+
else this.log('warn', `[fish-soul] DSH 语音未生成:${this.voice.lastError || '文字超长、配额不足或配置未就绪'}`);
|
|
1787
|
+
}
|
|
1767
1788
|
} catch (error) { this.log('warn', `[fish-soul] DSH 语音保存失败:${String(error instanceof Error ? error.message : error)}`); }
|
|
1768
1789
|
}
|
|
1769
1790
|
|
package/lib/importer.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { tokenizeForBm25 } from './segment.js';
|
|
8
8
|
import { randomCanonicalId } from './db.js';
|
|
9
|
+
import { isCalendarDate } from './time-util.js';
|
|
9
10
|
|
|
10
11
|
const KINDS = new Set(['fact', 'event', 'feeling', 'episode', 'diary']);
|
|
11
12
|
|
|
@@ -38,8 +39,8 @@ export function importMemories({ db, clock, worker, items, dryRun = false, maste
|
|
|
38
39
|
`);
|
|
39
40
|
const insert = db.prepare(`
|
|
40
41
|
INSERT INTO memory (character_id, owner_id, channel, channel_id, kind, content, keywords,
|
|
41
|
-
importance, emotion, source_session, created_at, updated_at, status, visibility, about)
|
|
42
|
-
VALUES ('feiyu', ?, ?, ?, ?, ?, ?, ?, ?, 'import', ?, ?, 'active', ?, ?)
|
|
42
|
+
importance, emotion, source_session, created_at, updated_at, status, visibility, about, sort_date)
|
|
43
|
+
VALUES ('feiyu', ?, ?, ?, ?, ?, ?, ?, ?, 'import', ?, ?, 'active', ?, ?, ?)
|
|
43
44
|
`);
|
|
44
45
|
const queued = [];
|
|
45
46
|
db.exec('BEGIN');
|
|
@@ -62,7 +63,7 @@ export function importMemories({ db, clock, worker, items, dryRun = false, maste
|
|
|
62
63
|
const channelId = String(it.channelId ?? it.channel_id ?? (qq !== '' ? `private:${qq}` : ''));
|
|
63
64
|
if (!dryRun) {
|
|
64
65
|
const r = insert.run(ownerId, channel, channelId, kind, content, tokenizeForBm25(content),
|
|
65
|
-
importance, emotion, createdAt, createdAt, it.visibility === 'private' ? 'private' : 'normal', typeof it.about === 'string' && it.about ? it.about : null);
|
|
66
|
+
importance, emotion, createdAt, createdAt, it.visibility === 'private' ? 'private' : 'normal', typeof it.about === 'string' && it.about ? it.about : null, isCalendarDate(it.sortDate) ? it.sortDate : null);
|
|
66
67
|
queued.push([Number(r.lastInsertRowid), content]);
|
|
67
68
|
}
|
|
68
69
|
report.inserted += 1;
|
package/lib/index.js
CHANGED
|
@@ -23,6 +23,7 @@ import { ChatArchive } from './chat-archive.js';
|
|
|
23
23
|
import { BackupService, applyPendingRestore } from './backup.js';
|
|
24
24
|
import { HistoryImporter } from './history-import.js';
|
|
25
25
|
import { LlmRouter } from './llm.js';
|
|
26
|
+
import { createStickerVision } from './sticker-vision.js';
|
|
26
27
|
import { VoiceService, voiceConfig, voiceLines } from './voice.js';
|
|
27
28
|
import { isAllowedVoiceInput } from './voice-files.js';
|
|
28
29
|
import { StickerBox, stickerConfig } from './stickers.js';
|
|
@@ -249,14 +250,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
249
250
|
* 模型看不见图却会照着提示词编一段描述,编出来的标签比没标签更糟。
|
|
250
251
|
* 超时也当没标签(导入 / 补标签都不该被一个卡住的模型吊死)。
|
|
251
252
|
*/
|
|
252
|
-
const visionTag =
|
|
253
|
-
try {
|
|
254
|
-
return await Promise.race([
|
|
255
|
-
llmRouter.call(prompt, { feature: 'other', maxTokens: 60, images, needImages: true, signal: AbortSignal.timeout(20_000) }),
|
|
256
|
-
new Promise((r) => { const t = setTimeout(() => r(null), 20_000); t.unref?.(); })
|
|
257
|
-
]);
|
|
258
|
-
} catch { return null; }
|
|
259
|
-
};
|
|
253
|
+
const visionTag = createStickerVision(llmRouter);
|
|
260
254
|
|
|
261
255
|
step(STARTUP_STEPS[2]);
|
|
262
256
|
// ── QQ 渠道(SnowLuma WS 直连)与会话网关 ──
|
|
@@ -500,7 +494,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
500
494
|
}
|
|
501
495
|
|
|
502
496
|
/** 网关在把一批 QQ 消息 / 主动触发递进会话之前调用:登记本轮说话人、预取向量、取到期约定。 */
|
|
503
|
-
function beginTurn(sessionId, { channel: ch, channelId, replyChannel, speakers, workspacePath, backlog = [], interject = false, voiceIn = false, proactive = false }) {
|
|
497
|
+
function beginTurn(sessionId, { channel: ch, channelId, replyChannel, speakers, workspacePath, backlog = [], interject = false, voiceIn = false, proactive = false, desktop = false }) {
|
|
504
498
|
const recentLines = journal.recent(channelId, 4);
|
|
505
499
|
const sp = (speakers ?? []).map((s) => ({
|
|
506
500
|
ownerId: ownerOf(s.person), person: s.person ?? null, userId: String(s.userId ?? ''),
|
|
@@ -525,7 +519,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
525
519
|
// 只有「回复规则」按它给;记忆 / 聊天日志 / 认人仍然按 channelId(话是在哪儿说的就记在哪儿)。
|
|
526
520
|
sessions.set(String(sessionId), {
|
|
527
521
|
channel: ch, channelId, replyChannel: replyChannel || channelId, speakers: sp, dueReasons, workspacePath: workspacePath ?? '',
|
|
528
|
-
atReal: Date.now(), backlog, interject, voiceIn, recalled: [], recentLines,
|
|
522
|
+
atReal: Date.now(), backlog, interject, voiceIn, desktop, recalled: [], recentLines,
|
|
529
523
|
// 动态页据此区分「瞬态块没跑」「认不出说话人」「跑了但没召回到」—— 空着的时候看不出来是哪一种(#78)
|
|
530
524
|
recalledAt: 0,
|
|
531
525
|
speakerUnknown: sp.length > 0 && sp.every((x) => x.ownerId === UNKNOWN_OWNER)
|
|
@@ -687,6 +681,10 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
687
681
|
function buildContextBlock(arg) {
|
|
688
682
|
const session = sessionFor(arg?.agent?.id ?? arg?.scope?.id ?? arg?.sessionId);
|
|
689
683
|
const lines = [stateLine()];
|
|
684
|
+
const desktopTurn = session?.desktop === true;
|
|
685
|
+
if (desktopTurn && currentConfig.voice?.desktopTts === true && voice.readyFor('tts')) {
|
|
686
|
+
lines.push('[DSH 本地语音] 要用语音说的话单独一段、开头写 [语音],不要带表情或链接;只生成本地文件,不会发到 QQ。');
|
|
687
|
+
}
|
|
690
688
|
if (session === undefined) return lines.join('\n');
|
|
691
689
|
// 这一轮确实组了瞬态块(动态页拿它区分「没跑」和「跑了但没召回到」,#78)
|
|
692
690
|
// 🔴 同时记到这一轮的 turn state 上:sendReply 在 turn/end 之后才跑,
|
|
@@ -796,7 +794,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
796
794
|
const loreMsgs = loreDepth > (session.recentLines ?? []).length && session.channelId ? journal.recent(session.channelId, loreDepth) : (session.recentLines ?? []);
|
|
797
795
|
const lore = matchLore(loreEntries, [...loreMsgs, ...speakers.map((s) => s.query)], loreCfg);
|
|
798
796
|
if (lore.length > 0) lines.push('[设定补充]', ...lore.map((e) => `- ${applyMacros(e.content, { charName: persona.name, userName })}`));
|
|
799
|
-
if (replyIsQq) {
|
|
797
|
+
if (replyIsQq && !desktopTurn) {
|
|
800
798
|
const images = gateway?.listImages(session.workspacePath) ?? [];
|
|
801
799
|
lines.push('[QQ 回复规则] 你的最后一条回复会原样发到 QQ' +
|
|
802
800
|
(replyWhere === 'qq-group'
|
|
@@ -832,7 +830,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
832
830
|
lines.push('[上网] 现在不能上网查,不知道的就直说不知道。');
|
|
833
831
|
}
|
|
834
832
|
}
|
|
835
|
-
if (replyIsBili || replyIsDouyin) {
|
|
833
|
+
if ((replyIsBili || replyIsDouyin) && !desktopTurn) {
|
|
836
834
|
lines.push(...voiceLines({ v: voiceConfig(currentConfig.voice, currentConfig.embedding), session, speakers, where: replyIsBili ? 'B站' : '抖音', relay: Boolean(gateway?.voiceRelayTarget(session.channelId)) }));
|
|
837
835
|
// webp 表情包要转格式才能发:没有转换器(sharp / 抖音浏览器)就不给模型看
|
|
838
836
|
// 清单带标签(`兔子OK.gif(可以可以、认同)`):光给文件名她只能瞎猜哪张合适
|
|
@@ -944,7 +942,8 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
944
942
|
channel: ours ? sessionChannelOf(boundChannel) : (person === null ? 'dsh' : (groupId != null ? 'qq-group' : 'qq-private')),
|
|
945
943
|
channelId: ours ? boundChannel : (person === null ? '' : (groupId != null ? `group:${groupId}` : `private:${qqUin}`)),
|
|
946
944
|
speakers: [{ person, userId: qqUin, displayName: person?.display_name ?? (ours ? '主人' : '对方'), text: messageText(message) }],
|
|
947
|
-
workspacePath: ours ? (gateway?.chatForSession(agentId)?.workspace_path ?? '') : ''
|
|
945
|
+
workspacePath: ours ? (gateway?.chatForSession(agentId)?.workspace_path ?? '') : '',
|
|
946
|
+
desktop: ours && source.kind === 'user'
|
|
948
947
|
});
|
|
949
948
|
// #41:别的插件把自己的 QQ 消息转进它建的会话 —— 那个会话不走我们的 create/resume,人格卡没挂上。
|
|
950
949
|
// 认出身份后(有人说话)用宿主给的 `agent.ctx` 补挂,仍然只对这一个 agent 生效,不碰全局。
|
|
@@ -1049,6 +1048,8 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
1049
1048
|
judgeMood: (person, who, text, channelId) => judgeMood(ownerOf(person), who, text, channelId),
|
|
1050
1049
|
/** 她发出去的话也进聊天日志(聊完整理时知道她说了什么)。#75:主动开口那轮标一下,整理时不当既成事实。 */
|
|
1051
1050
|
journalOut: (channelId, text, meta) => journal.add(channelId, { who: persona.name, ownerId: meta?.ownerId ?? null, self: true, text, proactive: meta?.proactive === true }),
|
|
1051
|
+
// DSH 回复只补进文本存档;不伪装成发往 QQ 的消息或改写现有记忆整理流程。
|
|
1052
|
+
archiveDesktop: (channelId, text) => chatArchive.add(channelId, { who: persona.name, self: true, text }),
|
|
1052
1053
|
/**
|
|
1053
1054
|
* 这一轮瞬态块里召回了哪些记忆("动态"里显示"她想起了什么")。
|
|
1054
1055
|
*
|
package/lib/llm.js
CHANGED
|
@@ -152,9 +152,10 @@ export class LlmRouter {
|
|
|
152
152
|
|
|
153
153
|
// #58:默认 600 对推理模型太小——光思考就 1000+ token,第一次必然白卷还白烧思考费。
|
|
154
154
|
// 提到 1500 让大多数推理模型的第一轮能容下思考;maxTokens 是上限不是必花,普通模型不受影响。
|
|
155
|
-
async call(prompt, { signal, maxTokens = 1500, feature = 'other', thinkFallback = false, images = [], needImages = false, _target, _tried } = {}) {
|
|
155
|
+
async call(prompt, { signal, maxTokens = 1500, feature = 'other', thinkFallback = false, images = [], needImages = false, failureInfo, _target, _tried } = {}) {
|
|
156
|
+
const failed = (code) => { if (failureInfo) failureInfo.code = code; };
|
|
156
157
|
const llm = this.llm();
|
|
157
|
-
if (llm === null) return null;
|
|
158
|
+
if (llm === null) { failed('model_unavailable'); return null; }
|
|
158
159
|
const f = FEATURE_IDS.has(feature) ? feature : 'other';
|
|
159
160
|
let target = _target ?? null;
|
|
160
161
|
if (target === null) { try { target = await this.resolve(f); } catch { target = null; } }
|
|
@@ -181,6 +182,7 @@ export class LlmRouter {
|
|
|
181
182
|
// 看图打标 / 导入表情全靠这条路,所以必须留一行,带上具体原因。
|
|
182
183
|
if (dropped && needImages) {
|
|
183
184
|
this.lastError = 'IMAGE_NOT_ADMITTED';
|
|
185
|
+
failed('image_not_admitted');
|
|
184
186
|
this.log('warn', `[fish-soul] ${f}:图没送进模型(${target.model || '(宿主默认)'}),这次要的就是图,放弃`);
|
|
185
187
|
return null;
|
|
186
188
|
}
|
|
@@ -192,7 +194,7 @@ export class LlmRouter {
|
|
|
192
194
|
temperature: 0.7,
|
|
193
195
|
...(signal ? { signal } : {})
|
|
194
196
|
})) {
|
|
195
|
-
if (signal?.aborted) return null;
|
|
197
|
+
if (signal?.aborted) { failed('timeout'); return null; }
|
|
196
198
|
const type = String(chunk?.type ?? typeof chunk);
|
|
197
199
|
seen.add(type);
|
|
198
200
|
if (type === 'text-delta') out += chunk.text ?? chunk.delta ?? '';
|
|
@@ -217,6 +219,7 @@ export class LlmRouter {
|
|
|
217
219
|
} else if (type === 'error' || type === 'failure') throw new Error(String(chunk.error?.message ?? chunk.message ?? 'stream error'));
|
|
218
220
|
}
|
|
219
221
|
} catch (error) {
|
|
222
|
+
failed(signal?.aborted ? 'timeout' : 'model_error');
|
|
220
223
|
this.lastError = String(error instanceof Error ? error.message : error).slice(0, 200);
|
|
221
224
|
this.record(f, target.model, { failed: true, inputTokens: estimateTokens(prompt), outputTokens: 0, estimated: true });
|
|
222
225
|
// 带图调用失败(有的通道/模型不吃 image 块):先退回纯文字重试一次。
|
|
@@ -231,21 +234,21 @@ export class LlmRouter {
|
|
|
231
234
|
return null;
|
|
232
235
|
}
|
|
233
236
|
// 按功能选的模型报错(比如模型下线了):换 DSH 默认模型试一次
|
|
234
|
-
return this.fallback(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, tried: tried.add(key) });
|
|
237
|
+
return this.fallback(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, failureInfo, tried: tried.add(key) });
|
|
235
238
|
}
|
|
236
239
|
const text = (out.trim() || blockText.trim());
|
|
237
240
|
if (text === '' && budget < ROOMY_TOKENS && !signal?.aborted) {
|
|
238
241
|
// 空回复多半是额度全花在思考上了:记住这个模型,放大额度再试一次
|
|
239
242
|
roomy.add(key);
|
|
240
243
|
this.record(f, target.model, { inputTokens: usage ? Number(usage.inputTokens) || 0 : estimateTokens(prompt), outputTokens: usage ? Number(usage.outputTokens) || 0 : 0, estimated: !usage, failed: true });
|
|
241
|
-
return this.call(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, _target: target, _tried: tried });
|
|
244
|
+
return this.call(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, failureInfo, _target: target, _tried: tried });
|
|
242
245
|
}
|
|
243
246
|
this.record(f, target.model, usage
|
|
244
247
|
? { inputTokens: Number(usage.inputTokens) || 0, outputTokens: Number(usage.outputTokens) || 0, estimated: false, failed: text === '' }
|
|
245
248
|
: { inputTokens: estimateTokens(prompt), outputTokens: estimateTokens(out), estimated: true, failed: text === '' });
|
|
246
|
-
if (text !== '') { this.lastError = ''; return text; }
|
|
249
|
+
if (text !== '') { this.lastError = ''; failed(''); return text; }
|
|
247
250
|
// 正文是空的但思考里写出了要的 JSON(有的推理模型把答案留在思考里):调用方允许就拿来用
|
|
248
|
-
if (thinkFallback && /\{[\s\S]*\}/.test(think)) { this.lastError = ''; return think.trim(); }
|
|
251
|
+
if (thinkFallback && /\{[\s\S]*\}/.test(think)) { this.lastError = ''; failed(''); return think.trim(); }
|
|
249
252
|
// 讲清楚空在哪:一个块都没收到 / 全是思考 / 被额度截断
|
|
250
253
|
const bits = [];
|
|
251
254
|
if (seen.size === 0) bits.push('一个数据块都没收到');
|
|
@@ -256,18 +259,19 @@ export class LlmRouter {
|
|
|
256
259
|
if (finish) bits.push(`结束原因 ${finish}`);
|
|
257
260
|
bits.push(`收到 ${[...seen].join('/')}`);
|
|
258
261
|
}
|
|
262
|
+
failed(signal?.aborted ? 'timeout' : 'empty_response');
|
|
259
263
|
this.lastError = `${target.model} 回了空内容(${bits.join(',')})`;
|
|
260
264
|
this.log('warn', `[fish-soul] ${f}:${this.lastError}`);
|
|
261
|
-
return this.fallback(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, tried: tried.add(key) });
|
|
265
|
+
return this.fallback(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, failureInfo, tried: tried.add(key) });
|
|
262
266
|
}
|
|
263
267
|
|
|
264
268
|
/** 这个模型不行(报错 / 空):换 DSH 默认模型再试一次;默认模型也试过了就算了。 */
|
|
265
|
-
async fallback(prompt, { signal, maxTokens, feature, thinkFallback, images = [], needImages = false, tried }) {
|
|
269
|
+
async fallback(prompt, { signal, maxTokens, feature, thinkFallback, images = [], needImages = false, failureInfo, tried }) {
|
|
266
270
|
if (signal?.aborted) return null;
|
|
267
271
|
const host = this.hostDefault();
|
|
268
272
|
if (host === null || tried.has(`${host.provider}/${host.model}`)) return null;
|
|
269
273
|
const first = this.lastError;
|
|
270
|
-
const r = await this.call(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, _target: { ...host, from: 'host' }, _tried: tried });
|
|
274
|
+
const r = await this.call(prompt, { signal, maxTokens, feature, thinkFallback, images, needImages, failureInfo, _target: { ...host, from: 'host' }, _tried: tried });
|
|
271
275
|
if (r === null && first && !this.lastError.includes(first)) this.lastError = `${first};换 ${host.model} 也没成:${this.lastError}`;
|
|
272
276
|
return r;
|
|
273
277
|
}
|
package/lib/memory-bulk.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isCalendarDate } from './time-util.js';
|
|
1
2
|
/**
|
|
2
3
|
* memory-bulk.js —— 记忆批量操作(设置页「记忆」里勾选多条 / 按筛选条件一次处理)。
|
|
3
4
|
*
|
|
@@ -61,6 +62,9 @@ export function bulkMemory({ db, clock, worker, ids, filter, action, value, dryR
|
|
|
61
62
|
} else if (action === 'visibility') {
|
|
62
63
|
if (value !== 'private' && value !== 'normal') return { ok: false, error: '只能是 private / normal' };
|
|
63
64
|
set = ['visibility = ?', value];
|
|
65
|
+
} else if (action === 'sortDate') {
|
|
66
|
+
if (value !== null && !isCalendarDate(value)) return { ok: false, error: '日期无效' };
|
|
67
|
+
set = ['sort_date = ?', value];
|
|
64
68
|
} else if (action !== 'forget' && action !== 'restore') return { ok: false, error: `不认识的操作:${action}` };
|
|
65
69
|
|
|
66
70
|
if (action !== 'forget') rows = rows.filter((r) => r.kind !== 'weekly'); // 派生周记不允许更改范围、类型或恢复
|
package/lib/panel.css
CHANGED
|
@@ -23,7 +23,14 @@ html[data-ds-theme-source] body:not([data-ds-dark-theme]) :is(.fs,.fs-page-shell
|
|
|
23
23
|
.fs.nav-collapsed{--fs-side:48px}
|
|
24
24
|
.fs *,.fs *::before,.fs *::after{box-sizing:border-box}
|
|
25
25
|
.fs :where(h2,h3,p,pre,ul,figure){margin:0;padding:0}
|
|
26
|
-
|
|
26
|
+
/* 通用控件重置 —— 必须保持「零特异性」,只兜底没被打扮过的元素。
|
|
27
|
+
🔴 写成 `.fs :where(button,…)` 时特异性是 (0,1,0)(`.fs` 那一层计入),
|
|
28
|
+
跟宿主控件自己的 `._button_xxx{color/font-size}` 打平;而插件样式注入在宿主之后
|
|
29
|
+
⇒ 重置反而赢了宿主 ⇒ 宿主 primary 按钮的「深色实心 + 反色字」被换成继承色,
|
|
30
|
+
变成黑底黑字(真机:更新页「更新到 vX」是一个看不清字的黑块)。
|
|
31
|
+
包一层 :where() 把特异性降到 (0,0,0):宿主任何组件类都赢它,
|
|
32
|
+
插件自有的 .fs-btn / .fs-icon-btn 也照旧赢它(它们仍是 (0,1,0))。 */
|
|
33
|
+
:where(.fs) :where(button,input,select,textarea){font:inherit;color:inherit}
|
|
27
34
|
.fs :where(button,a,input,select,textarea,summary):focus-visible{outline:1px solid var(--accent);outline-offset:1px}
|
|
28
35
|
.fs .num,.fs-unit.num{font-family:var(--fs-mono);font-size:12px;font-variant-numeric:tabular-nums;letter-spacing:-.01em}
|
|
29
36
|
.fs-muted{color:var(--fg-tertiary)}
|
package/lib/routes-soul.js
CHANGED
|
@@ -12,7 +12,7 @@ import { platformOf } from './gateway.js';
|
|
|
12
12
|
import { STAGES, PROFILE_FIELDS, stageBase, effectiveAffinity, getMood, mergeProfileFields, digestConfig } from './soul-memory.js';
|
|
13
13
|
|
|
14
14
|
import { bulkMemory } from './memory-bulk.js';
|
|
15
|
-
import { dateCompact } from './time-util.js';
|
|
15
|
+
import { dateCompact, isCalendarDate } from './time-util.js';
|
|
16
16
|
|
|
17
17
|
const KINDS = ['fact', 'event', 'feeling', 'episode'];
|
|
18
18
|
const IMPORT_BODY_MAX = 40 * 1024 * 1024;
|
|
@@ -22,7 +22,7 @@ const ownerToCanonical = (ownerId) => String(ownerId ?? '').replace(/^user:/, ''
|
|
|
22
22
|
function memoryView(m) {
|
|
23
23
|
return {
|
|
24
24
|
id: m.id, ownerId: m.owner_id, channel: m.channel, channelId: m.channel_id, kind: m.kind, content: m.content,
|
|
25
|
-
importance: m.importance, importanceLocked: m.importance_locked === 1, importanceAutoRecalled: m.importance_auto_recalled === 1, emotion: m.emotion, createdAt: m.created_at, updatedAt: m.updated_at, status: m.status,
|
|
25
|
+
importance: m.importance, importanceLocked: m.importance_locked === 1, importanceAutoRecalled: m.importance_auto_recalled === 1, emotion: m.emotion, createdAt: m.created_at, sortDate: m.sort_date ?? null, updatedAt: m.updated_at, status: m.status,
|
|
26
26
|
supersededBy: m.superseded_by ?? null, evidence: m.evidence ?? '', source: sourceLabel(m.source_session, m.channel),
|
|
27
27
|
visibility: m.visibility ?? 'normal', about: m.about ?? null
|
|
28
28
|
};
|
|
@@ -268,8 +268,10 @@ export async function handleSoulRoute({ method, path, url, req, res, send, readB
|
|
|
268
268
|
const kind = KINDS.includes(b.kind) ? b.kind : m.kind;
|
|
269
269
|
const importance = b.importance === undefined ? m.importance : Math.min(5, Math.max(1, Math.round(Number(b.importance)) || 1));
|
|
270
270
|
const now = clock.now();
|
|
271
|
+
const sortDate = b.sortDate === undefined ? m.sort_date : b.sortDate;
|
|
272
|
+
if (sortDate !== null && !isCalendarDate(sortDate)) { send(200, { ok: false, error: '日期无效' }); return true; }
|
|
271
273
|
if (content === m.content) {
|
|
272
|
-
db.prepare('UPDATE memory SET kind = ?, importance = ?, importance_locked = CASE WHEN ? THEN 1 ELSE importance_locked END, importance_auto_recalled = CASE WHEN ? THEN 0 ELSE importance_auto_recalled END, updated_at = ? WHERE id = ?').run(kind, importance, b.importance !== undefined ? 1 : 0, b.importance !== undefined ? 1 : 0, now, id);
|
|
274
|
+
db.prepare('UPDATE memory SET kind = ?, importance = ?, importance_locked = CASE WHEN ? THEN 1 ELSE importance_locked END, importance_auto_recalled = CASE WHEN ? THEN 0 ELSE importance_auto_recalled END, sort_date = ?, updated_at = ? WHERE id = ?').run(kind, importance, b.importance !== undefined ? 1 : 0, b.importance !== undefined ? 1 : 0, sortDate, now, id);
|
|
273
275
|
send(200, { ok: true, id });
|
|
274
276
|
return true;
|
|
275
277
|
}
|
|
@@ -279,10 +281,10 @@ export async function handleSoulRoute({ method, path, url, req, res, send, readB
|
|
|
279
281
|
try {
|
|
280
282
|
const r = db.prepare(`
|
|
281
283
|
INSERT INTO memory (character_id, owner_id, channel, channel_id, kind, content, keywords, importance, emotion,
|
|
282
|
-
source_session, created_at, updated_at, status, evidence, visibility, about, importance_locked)
|
|
283
|
-
VALUES ('feiyu', ?, ?, ?, ?, ?, ?, ?, ?, 'manual', ?, ?, 'active', ?, ?, ?, ?)
|
|
284
|
+
source_session, created_at, updated_at, status, evidence, visibility, about, importance_locked, sort_date)
|
|
285
|
+
VALUES ('feiyu', ?, ?, ?, ?, ?, ?, ?, ?, 'manual', ?, ?, 'active', ?, ?, ?, ?, ?)
|
|
284
286
|
`).run(m.owner_id, m.channel, m.channel_id, kind, content, tokenizeForBm25(content), importance, m.emotion, m.created_at, now,
|
|
285
|
-
`主人在设置页改过(原来是:${m.content.slice(0, 120)})`, m.visibility ?? 'normal', m.about ?? null, b.importance !== undefined ? 1 : Number(m.importance_locked ?? 0));
|
|
287
|
+
`主人在设置页改过(原来是:${m.content.slice(0, 120)})`, m.visibility ?? 'normal', m.about ?? null, b.importance !== undefined ? 1 : Number(m.importance_locked ?? 0), sortDate);
|
|
286
288
|
newId = Number(r.lastInsertRowid);
|
|
287
289
|
db.prepare("UPDATE memory SET status = 'superseded', valid_to = ?, superseded_by = ?, updated_at = ? WHERE id = ?").run(now, newId, now, id);
|
|
288
290
|
db.prepare('DELETE FROM vec WHERE memory_id = ?').run(id);
|
|
@@ -409,7 +411,7 @@ export async function handleSoulRoute({ method, path, url, req, res, send, readB
|
|
|
409
411
|
const items = rows.map((m) => ({
|
|
410
412
|
ownerId: m.owner_id, ...(m.qq_uin ? { qqUin: m.qq_uin } : {}), ...(m.display_name ? { nickname: m.display_name } : {}),
|
|
411
413
|
content: m.content, kind: m.kind, importance: m.importance, emotion: m.emotion, channel: m.channel, channelId: m.channel_id,
|
|
412
|
-
createdAt: m.created_at, visibility: m.visibility, ...(m.about ? { about: m.about } : {}), ...(m.evidence ? { evidence: m.evidence } : {})
|
|
414
|
+
createdAt: m.created_at, ...(m.sort_date ? { sortDate: m.sort_date } : {}), visibility: m.visibility, ...(m.about ? { about: m.about } : {}), ...(m.evidence ? { evidence: m.evidence } : {})
|
|
413
415
|
}));
|
|
414
416
|
const name = `fish-soul-memories-${dateCompact()}.json`;
|
|
415
417
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-disposition': `attachment; filename="${name}"` });
|
package/lib/routes-v07.js
CHANGED
|
@@ -15,6 +15,7 @@ import { FEATURES } from './llm.js';
|
|
|
15
15
|
import { voiceConfig } from './voice.js';
|
|
16
16
|
import { voiceDir, voiceFileList, voiceIncomingCount, clearVoiceFiles, invalidateIncomingVoice } from './voice-files.js';
|
|
17
17
|
import { stickerConfig } from './stickers.js';
|
|
18
|
+
import { createStickerVision } from './sticker-vision.js';
|
|
18
19
|
import { chatKind, slangConfig, GLOBAL_ID } from './slang.js';
|
|
19
20
|
import { WEB_PROVIDERS, webSearchConfig, ownSearchReady } from './websearch.js';
|
|
20
21
|
import { listChatSessions } from './db.js';
|
|
@@ -26,8 +27,6 @@ const IMPORT_BODY_MAX = 6 * 1024 * 1024; // 旧路(JSON + base64)的 body
|
|
|
26
27
|
// 原始二进制上传(新路)的图片上限。流式写盘,内存不随大小增长,所以给得比 base64 那条宽得多。
|
|
27
28
|
// 20MB 足够绝大多数表情包/截图;再大就建议直接放进 _stickers 目录(零上传)。
|
|
28
29
|
const IMPORT_BYTES_MAX = 20 * 1024 * 1024;
|
|
29
|
-
/** 看图打标签最多等多久:面板在等这个请求,模型卡住不能把导入一起吊死。 */
|
|
30
|
-
const VISION_TIMEOUT_MS = 20_000;
|
|
31
30
|
const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' };
|
|
32
31
|
const MEDIA_TYPES = new Set(Object.values(MIME));
|
|
33
32
|
|
|
@@ -92,22 +91,7 @@ export async function handleV07Route({ method, path, url, req, res, send, readBo
|
|
|
92
91
|
return JSON.parse(raw || '{}');
|
|
93
92
|
};
|
|
94
93
|
const guard = () => { if (!sameOrigin(req)) { send(403, { ok: false, error: 'forbidden' }); return false; } return true; };
|
|
95
|
-
|
|
96
|
-
* 看图打标签用的回调:宿主模型(没配模型 / 路由没起来 → 没有这个能力 → 不打标签,静默跳过)。
|
|
97
|
-
* 识图是宿主模型的事,插件只保证把图送到它面前。
|
|
98
|
-
*
|
|
99
|
-
* `needImages`:这次调用要的就是图。宿主送不进图 / 通道不吃 image 块时,llm 会直接回 null,
|
|
100
|
-
* 而不是退回纯文字 —— 模型看不见图却会照着提示词编一段描述,编出来的标签比没标签更糟。
|
|
101
|
-
*/
|
|
102
|
-
const vision = llmRouter ? async (prompt, images) => {
|
|
103
|
-
try {
|
|
104
|
-
// 导入是面板在等着的请求:模型卡住不能把导入一起吊死(超时就当没标签)。
|
|
105
|
-
return await Promise.race([
|
|
106
|
-
llmRouter.call(prompt, { feature: 'other', maxTokens: 60, images, needImages: true, signal: AbortSignal.timeout(VISION_TIMEOUT_MS) }),
|
|
107
|
-
new Promise((r) => { const t = setTimeout(() => r(null), VISION_TIMEOUT_MS); t.unref?.(); })
|
|
108
|
-
]);
|
|
109
|
-
} catch { return null; }
|
|
110
|
-
} : null;
|
|
94
|
+
const vision = createStickerVision(llmRouter);
|
|
111
95
|
/** 导入一张表情:存进 _stickers 之后顺手看图打标签(打不上就当没标签,导入照旧成功)。 */
|
|
112
96
|
const importSticker = async (args) => {
|
|
113
97
|
const r = stickers?.importImage?.(args) ?? { ok: false, reason: '表情包没起来' };
|
|
@@ -323,13 +307,15 @@ export async function handleV07Route({ method, path, url, req, res, send, readBo
|
|
|
323
307
|
embedder: canEmbed ? embedder : null,
|
|
324
308
|
opts: { limit: Math.min(100, Math.max(1, Math.floor(Number(b.limit) || 40))), model: String(ecfg.model ?? '') }
|
|
325
309
|
});
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
310
|
+
const descriptions = {
|
|
311
|
+
file_unreadable: '文件读不到', file_too_large: '图片超过 4 MB', unsupported_format: '图片格式不支持',
|
|
312
|
+
image_not_admitted: '宿主附件库未接收图片', model_unavailable: '模型服务不可用',
|
|
313
|
+
model_error: '带图模型调用失败,请检查“其他”模型和宿主日志', timeout: '看图超时',
|
|
314
|
+
empty_response: '模型返回空内容', invalid_tags: '模型回复不是可用标签', no_response: '没有拿到看图结果'
|
|
315
|
+
};
|
|
316
|
+
const hint = Object.entries(r.failures ?? {}).map(([code, count]) => `${descriptions[code] ?? '未知原因'} ${count} 张`).join(';');
|
|
317
|
+
// 只记分类与数量,不写文件名、图片内容或模型错误原文(可能包含密钥)。
|
|
318
|
+
if (hint) deps.diag?.add('sticker-tag-failed', { reason: hint }, 'warn');
|
|
333
319
|
send(200, { ok: true, ...r, hint });
|
|
334
320
|
return true;
|
|
335
321
|
}
|
package/lib/routes.js
CHANGED
|
@@ -390,6 +390,7 @@ export function registerRoutes(ctx, deps) {
|
|
|
390
390
|
// 筛选:内容包含 q、来源 source、私密 visibility;limit 最多 500(批量操作要看得到更多)
|
|
391
391
|
const listFilter = filterWhere({ ownerId: ownerFilter, q: url.searchParams.get('q') ?? '', source: url.searchParams.get('source') ?? '', visibility: url.searchParams.get('visibility') ?? '' });
|
|
392
392
|
const listLimit = Math.min(500, Math.max(1, Math.floor(Number(url.searchParams.get('limit') ?? 100)) || 100));
|
|
393
|
+
const listOffset = Math.min(100_000, Math.max(0, Math.floor(Number(url.searchParams.get('offset') ?? 0)) || 0));
|
|
393
394
|
const meta = readVecMeta(db);
|
|
394
395
|
const gen = meta?.generation_id ?? 1;
|
|
395
396
|
const persons = db.prepare(`
|
|
@@ -405,10 +406,10 @@ export function registerRoutes(ctx, deps) {
|
|
|
405
406
|
);
|
|
406
407
|
// 同一创建时间的记忆按最早版本的 id 排序:编辑会新建 id,不能因此换位置。
|
|
407
408
|
// UNION 防止旧数据中的异常环造成递归不结束;索引支持按 superseded_by 反查。
|
|
408
|
-
const memRows = db.prepare(`SELECT * FROM memory WHERE ${listFilter.sql} ORDER BY created_at DESC,
|
|
409
|
+
const memRows = db.prepare(`SELECT * FROM memory WHERE ${listFilter.sql} ORDER BY COALESCE(sort_date, date(created_at / 1000, 'unixepoch', 'localtime')) DESC, created_at DESC,
|
|
409
410
|
(WITH RECURSIVE ancestors(id) AS (
|
|
410
411
|
SELECT memory.id UNION SELECT old.id FROM memory old JOIN ancestors a ON old.superseded_by = a.id
|
|
411
|
-
) SELECT MIN(id) FROM ancestors) ASC, id ASC LIMIT ${listLimit}`).all(...listFilter.params);
|
|
412
|
+
) SELECT MIN(id) FROM ancestors) ASC, id ASC LIMIT ${listLimit} OFFSET ${listOffset}`).all(...listFilter.params);
|
|
412
413
|
const matchedTotal = db.prepare(`SELECT COUNT(*) AS n FROM memory WHERE ${listFilter.sql}`).get(...listFilter.params).n;
|
|
413
414
|
const vecGenById = new Map(
|
|
414
415
|
db.prepare('SELECT memory_id, generation_id FROM vec').all().map((r) => [r.memory_id, r.generation_id])
|
|
@@ -422,6 +423,8 @@ export function registerRoutes(ctx, deps) {
|
|
|
422
423
|
ok: true,
|
|
423
424
|
currentGenerationId: gen,
|
|
424
425
|
matchedTotal,
|
|
426
|
+
offset: listOffset,
|
|
427
|
+
limit: listLimit,
|
|
425
428
|
persons: [
|
|
426
429
|
{ canonicalId: 'feiyu', ownerId: 'self', displayName: '鱼自身 (self)', relationStage: 'close', interactionCount: 0, memoryCount: countByOwner.get('self') ?? 0 },
|
|
427
430
|
...persons.map((p) => ({
|
|
@@ -443,7 +446,7 @@ export function registerRoutes(ctx, deps) {
|
|
|
443
446
|
importance: m.importance, importanceLocked: m.importance_locked === 1, importanceAutoRecalled: m.importance_auto_recalled === 1, emotion: m.emotion,
|
|
444
447
|
evidence: m.evidence ?? '', source: sourceLabel(m.source_session, m.channel),
|
|
445
448
|
decayExempt: m.importance >= 3,
|
|
446
|
-
createdAt: m.created_at, visibility: m.visibility ?? 'normal', about: m.about ?? null, recallCount: m.recall_count ?? 0,
|
|
449
|
+
createdAt: m.created_at, sortDate: m.sort_date ?? null, visibility: m.visibility ?? 'normal', about: m.about ?? null, recallCount: m.recall_count ?? 0,
|
|
447
450
|
vecStatus: vg === null ? 'unvectorized_compensated' : (vg === gen ? 'vectorized' : 'stale'),
|
|
448
451
|
vecGenerationId: vg
|
|
449
452
|
};
|
|
@@ -551,6 +554,8 @@ export function registerRoutes(ctx, deps) {
|
|
|
551
554
|
tokenMasked: maskKey(q.accessToken ?? ''),
|
|
552
555
|
groupAllowList: Array.isArray(q.groupAllowList) ? q.groupAllowList : [],
|
|
553
556
|
allGroups: q.allGroups === true,
|
|
557
|
+
privateAllowList: Array.isArray(q.privateAllowList) ? q.privateAllowList : [],
|
|
558
|
+
allFriends: q.allFriends === true,
|
|
554
559
|
followUpCount: q.followUpCount ?? 3,
|
|
555
560
|
followUpSeconds: q.followUpSeconds ?? 120,
|
|
556
561
|
followUpSmart: q.followUpSmart === true,
|
|
@@ -649,6 +654,11 @@ export function registerRoutes(ctx, deps) {
|
|
|
649
654
|
if (!groups.every((g) => /^\d{4,12}$/.test(g))) return send(200, { ok: false, error: '群号只能是数字' });
|
|
650
655
|
const master = body.masterQqUin === undefined ? undefined : String(body.masterQqUin).trim();
|
|
651
656
|
if (master !== undefined && master !== '' && !/^\d{5,12}$/.test(master)) return send(200, { ok: false, error: '主人 QQ 号只能是数字' });
|
|
657
|
+
// 私聊白名单:空 = 谁都不放行(主人永远放行);要放开所有好友得开 allFriends
|
|
658
|
+
const privates = Array.isArray(body.privateAllowList)
|
|
659
|
+
? body.privateAllowList.map((u) => String(u).replace(/^private:/, '').trim()).filter(Boolean).slice(0, 50)
|
|
660
|
+
: (cur.privateAllowList ?? []);
|
|
661
|
+
if (!privates.every((u) => /^\d{4,12}$/.test(u))) return send(200, { ok: false, error: '私聊白名单只能是 QQ 号' });
|
|
652
662
|
// 群管理(公告 / 入群申请):设置页没带这一段就沿用现在的,别被保存冲掉
|
|
653
663
|
const groupAdmin = normalizeConfig(body.groupAdmin === undefined
|
|
654
664
|
? cur.groupAdmin
|
|
@@ -661,6 +671,8 @@ export function registerRoutes(ctx, deps) {
|
|
|
661
671
|
...(body.clearToken === true ? { accessToken: '' } : {}),
|
|
662
672
|
groupAllowList: groups,
|
|
663
673
|
allGroups: body.allGroups === undefined ? cur.allGroups === true : body.allGroups === true,
|
|
674
|
+
privateAllowList: privates,
|
|
675
|
+
allFriends: body.allFriends === undefined ? cur.allFriends === true : body.allFriends === true,
|
|
664
676
|
followUpCount: Math.min(20, Math.max(0, Math.floor(Number(body.followUpCount ?? cur.followUpCount ?? 3)) || 0)),
|
|
665
677
|
followUpSeconds: Math.min(1800, Math.max(0, Math.floor(Number(body.followUpSeconds ?? cur.followUpSeconds ?? 120)) || 0)),
|
|
666
678
|
followUpSmart: body.followUpSmart === undefined ? cur.followUpSmart === true : body.followUpSmart === true,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** 表情看图:每次单独保存失败类型,不能读取其他并发调用共用的 lastError。 */
|
|
2
|
+
export function createStickerVision(llmRouter, { timeoutMs = 20_000 } = {}) {
|
|
3
|
+
if (!llmRouter) return null;
|
|
4
|
+
return async (prompt, images, { onFailure } = {}) => {
|
|
5
|
+
const failureInfo = {};
|
|
6
|
+
const controller = new AbortController();
|
|
7
|
+
let timedOut = false;
|
|
8
|
+
let timer;
|
|
9
|
+
try {
|
|
10
|
+
const result = await Promise.race([
|
|
11
|
+
llmRouter.call(prompt, { feature: 'other', maxTokens: 60, images, needImages: true, signal: controller.signal, failureInfo }),
|
|
12
|
+
new Promise((resolve) => { timer = setTimeout(() => { timedOut = true; controller.abort(); resolve(null); }, timeoutMs); timer.unref?.(); })
|
|
13
|
+
]);
|
|
14
|
+
if (result === null || result === undefined || String(result).trim() === '') onFailure?.(timedOut ? 'timeout' : (failureInfo.code || 'no_response'));
|
|
15
|
+
return result;
|
|
16
|
+
} catch {
|
|
17
|
+
onFailure?.(timedOut ? 'timeout' : 'model_error');
|
|
18
|
+
return null;
|
|
19
|
+
} finally { clearTimeout(timer); }
|
|
20
|
+
};
|
|
21
|
+
}
|
package/lib/stickers.js
CHANGED
|
@@ -579,19 +579,22 @@ export class StickerBox {
|
|
|
579
579
|
* @param {(prompt: string, images: Array<{data: string, mediaType: string, name: string}>) => Promise<string|null>} [vision]
|
|
580
580
|
* @returns {Promise<string[]>} 打上的标签(没打上就是空数组)
|
|
581
581
|
*/
|
|
582
|
-
async tagByVision(o, vision) {
|
|
583
|
-
|
|
584
|
-
if (
|
|
582
|
+
async tagByVision(o, vision, { onFailure } = {}) {
|
|
583
|
+
const fail = (code) => { onFailure?.(code); return []; };
|
|
584
|
+
if (typeof vision !== 'function') return fail('model_unavailable');
|
|
585
|
+
if (!o?.bytes) return fail('file_unreadable');
|
|
586
|
+
if (o.bytes.length > VISION_MAX_BYTES) return fail('file_too_large');
|
|
585
587
|
const all = this.collected();
|
|
586
588
|
const hit = all.find((x) => x.file === o.file && sameWs(x.workspacePath, o.workspacePath));
|
|
587
|
-
if (!hit) return
|
|
589
|
+
if (!hit) return fail('file_unreadable');
|
|
588
590
|
if ((hit.tags ?? []).length > 0) return hit.tags; // 已经有标签了(模型自己标的 / summary 捡的),不覆盖
|
|
589
591
|
let out = null;
|
|
592
|
+
let reason = '';
|
|
590
593
|
try {
|
|
591
|
-
out = await vision(VISION_TAG_PROMPT, [{ data: o.bytes.toString('base64'), mediaType: o.mediaType ?? 'image/png', name: o.file }]);
|
|
594
|
+
out = await vision(VISION_TAG_PROMPT, [{ data: o.bytes.toString('base64'), mediaType: o.mediaType ?? 'image/png', name: o.file }], { onFailure: (code) => { reason = code; } });
|
|
592
595
|
} catch (error) {
|
|
593
596
|
this.log?.('warn', `[fish-soul] 表情「${o.file}」看图打标抛错:${String(error instanceof Error ? error.message : error).slice(0, 120)}`);
|
|
594
|
-
return
|
|
597
|
+
return fail('model_error');
|
|
595
598
|
}
|
|
596
599
|
// 三种失败要分得开,否则「有些表情没标签」永远只能猜:
|
|
597
600
|
// ① 回了 null ⇒ 图没送进模型 / 模型没视觉(llm.js 那边已经留了 warn)
|
|
@@ -599,12 +602,13 @@ export class StickerBox {
|
|
|
599
602
|
// ③ 回了一段话但不像标签 ⇒ 提示词 / 模型理解问题
|
|
600
603
|
if (out === null || out === undefined || String(out).trim() === '') {
|
|
601
604
|
this.log?.('warn', `[fish-soul] 表情「${o.file}」看图打标没拿到回复(图可能没送进模型,见上一行)`);
|
|
602
|
-
|
|
605
|
+
const allowed = ['image_not_admitted', 'model_unavailable', 'model_error', 'timeout', 'empty_response', 'no_response'];
|
|
606
|
+
return fail(allowed.includes(reason) ? reason : 'no_response');
|
|
603
607
|
}
|
|
604
608
|
const tags = tagsFromVision(out);
|
|
605
609
|
if (tags.length === 0) {
|
|
606
610
|
this.log?.('warn', `[fish-soul] 表情「${o.file}」看图打标回的不像标签:「${String(out).replace(/\s+/g, ' ').slice(0, 60)}」`);
|
|
607
|
-
return
|
|
611
|
+
return fail('invalid_tags');
|
|
608
612
|
}
|
|
609
613
|
hit.tags = tags;
|
|
610
614
|
hit.tagsBy = 'vision';
|
|
@@ -627,18 +631,19 @@ export class StickerBox {
|
|
|
627
631
|
* @param {(prompt: string, images: Array<{data: string, mediaType: string, name: string}>) => Promise<string|null>} [o.vision]
|
|
628
632
|
* @param {{embed: Function, getConfig?: Function}} [o.embedder]
|
|
629
633
|
* @param {{limit?: number, model?: string, onProgress?: (p: {done: number, total: number, tagged: number}) => void}} [o.opts]
|
|
630
|
-
* @returns {Promise<{tagged: number, skipped: number, embedded: number, total: number}>}
|
|
634
|
+
* @returns {Promise<{tagged: number, skipped: number, embedded: number, total: number, failures: Record<string, number>}>}
|
|
631
635
|
*/
|
|
632
636
|
async backfillTags({ workspacePath = '', vision = null, embedder = null, opts = {} } = {}) {
|
|
633
637
|
const limit = Math.max(1, Math.round(Number(opts.limit) || 40));
|
|
634
638
|
const all = this.collected();
|
|
635
639
|
const want = (x) => (workspacePath === '' || sameWs(x.workspacePath, workspacePath));
|
|
636
640
|
const todo = all.filter((x) => want(x) && (x.tags ?? []).length === 0).slice(0, limit);
|
|
637
|
-
const result = { tagged: 0, skipped: 0, embedded: 0, total: todo.length };
|
|
641
|
+
const result = { tagged: 0, skipped: 0, embedded: 0, total: todo.length, failures: {} };
|
|
642
|
+
const failed = (reason) => { result.failures[reason] = (result.failures[reason] ?? 0) + 1; };
|
|
638
643
|
for (const [i, hit] of todo.entries()) {
|
|
639
644
|
const img = this.readStickerBytes(hit);
|
|
640
|
-
if (img
|
|
641
|
-
const tags = await this.tagByVision({ file: hit.file, bytes: img.bytes, mediaType: img.mediaType, workspacePath: hit.workspacePath }, vision);
|
|
645
|
+
if (img.error) { result.skipped++; failed(img.error); opts.onProgress?.({ done: i + 1, total: todo.length, tagged: result.tagged }); continue; }
|
|
646
|
+
const tags = await this.tagByVision({ file: hit.file, bytes: img.bytes, mediaType: img.mediaType, workspacePath: hit.workspacePath }, vision, { onFailure: failed });
|
|
642
647
|
if (tags.length === 0) result.skipped++;
|
|
643
648
|
else result.tagged++;
|
|
644
649
|
opts.onProgress?.({ done: i + 1, total: todo.length, tagged: result.tagged });
|
|
@@ -654,18 +659,20 @@ export class StickerBox {
|
|
|
654
659
|
/**
|
|
655
660
|
* 从收藏记录读回图片字节 + 推断 mediaType(面板补打标要原图)。
|
|
656
661
|
* 收藏记录里**没存 mediaType**(只有文件名),所以从扩展名反推 —— 反推不出就是读不到。
|
|
657
|
-
* @returns {{bytes: Buffer, mediaType: string}|
|
|
662
|
+
* @returns {{bytes: Buffer, mediaType: string}|{error: string}}
|
|
658
663
|
*/
|
|
659
664
|
readStickerBytes(hit) {
|
|
660
665
|
const file = String(hit?.file ?? '');
|
|
661
|
-
if (file === '') return
|
|
666
|
+
if (file === '') return { error: 'file_unreadable' };
|
|
662
667
|
const ext = extname(file).slice(1).toLowerCase();
|
|
663
|
-
if (!IMAGE_EXT.has(ext)) return
|
|
668
|
+
if (!IMAGE_EXT.has(ext)) return { error: 'unsupported_format' };
|
|
664
669
|
const mediaType = `image/${ext === 'jpg' ? 'jpeg' : ext}`;
|
|
665
670
|
try {
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
671
|
+
const path = join(hit.workspacePath, '_stickers', basename(file));
|
|
672
|
+
if (statSync(path).size > VISION_MAX_BYTES) return { error: 'file_too_large' };
|
|
673
|
+
const bytes = readFileSync(path);
|
|
674
|
+
return bytes.length > VISION_MAX_BYTES ? { error: 'file_too_large' } : { bytes, mediaType };
|
|
675
|
+
} catch { return { error: 'file_unreadable' }; }
|
|
669
676
|
}
|
|
670
677
|
|
|
671
678
|
/** 设置页删一张:收藏的和主人自己放的都能删;文件已经没了就把收藏记录也删掉。 */
|
package/lib/time-util.js
CHANGED
|
@@ -23,3 +23,10 @@ export function stampLocal(ms) {
|
|
|
23
23
|
export function dateCompact(d = new Date()) {
|
|
24
24
|
return `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}`;
|
|
25
25
|
}
|
|
26
|
+
|
|
27
|
+
/** 严格校验日期,避免 SQLite 接受不存在的日历日期。 */
|
|
28
|
+
export function isCalendarDate(value) {
|
|
29
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
30
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
31
|
+
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
|
32
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-fish-soul",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.15.37)",
|
|
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/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-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-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/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.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/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/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/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",
|
|
67
|
+
"test": "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-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-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/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/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",
|
|
68
68
|
"eval": "node test/eval/persona-eval.mjs"
|
|
69
69
|
}
|
|
70
70
|
}
|