dsh-folia 4.26.0-pre.3 → 4.26.0-pre.6

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/lib/client.js CHANGED
@@ -18632,9 +18632,263 @@ window.__ModuleLoader__.load({
18632
18632
  weT("站点上还没有桌宠。")));
18633
18633
  }
18634
18634
 
18635
+ // ── 桌宠对话(/folia/pet-chat/*)────────────────────────────────────────
18636
+ // 放在页签底部,紧跟「显示桌宠 / 声音 / 音量 / 复位位置 / 大小」之后。
18637
+ children.push(React.createElement(PetChatSettings, { key: "petChat" }));
18638
+
18635
18639
  return React.createElement("div", { className: "we-picker__section" }, children);
18636
18640
  }
18637
18641
 
18642
+ /* ── 桌宠对话设置区 ─────────────────────────────────────────────────────── */
18643
+
18644
+ const CHAT_DEFAULTS = {
18645
+ enabled: false,
18646
+ provider: 'openai',
18647
+ baseUrl: 'https://api.deepseek.com',
18648
+ model: 'deepseek-chat',
18649
+ apiKey: '',
18650
+ apiKeyMasked: '',
18651
+ hasApiKey: false,
18652
+ persona: { name: '', traits: '', notes: '' },
18653
+ maxTurns: 8,
18654
+ maxChars: 80,
18655
+ voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
18656
+ voiceEngine: 'system',
18657
+ memoryEnabled: true,
18658
+ proactive: { enabled: false, dailyLimit: 10, minGapMin: 120, quietHours: '22:00-08:00' },
18659
+ voiceEnabled: false,
18660
+ };
18661
+
18662
+ const PROVIDER_PRESETS = {
18663
+ openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
18664
+ ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'llama3.1' },
18665
+ };
18666
+
18667
+ function PetChatSettings() {
18668
+ const [draft, setDraft] = React.useState(CHAT_DEFAULTS);
18669
+ const [status, setStatus] = React.useState({ ok: null, text: '' });
18670
+ const [note, setNote] = React.useState(null);
18671
+ const [showKey, setShowKey] = React.useState(false);
18672
+ const [memory, setMemory] = React.useState(null);
18673
+ const [busy, setBusy] = React.useState(false);
18674
+ const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
18675
+
18676
+ const load = React.useCallback(async () => {
18677
+ try {
18678
+ const resp = await apiJson('/pet-chat/config', { parse: 'always' });
18679
+ const doc = (resp && resp.data) || null;
18680
+ if (doc && doc.ok !== false) {
18681
+ setDraft({ ...CHAT_DEFAULTS, ...doc, apiKey: '' });
18682
+ setStatus(doc.hasApiKey
18683
+ ? { ok: true, text: weT('已保存的 Key:{mask}', { mask: doc.apiKeyMasked || '••••' }) }
18684
+ : { ok: null, text: weT('还没有填 API Key') });
18685
+ }
18686
+ } catch { /* 首次加载失败不打扰:保存时会报 */ }
18687
+ }, []);
18688
+ React.useEffect(() => { void load(); }, [load]);
18689
+
18690
+ const save = async () => {
18691
+ setBusy(true);
18692
+ try {
18693
+ const resp = await apiJson('/pet-chat/config', {
18694
+ method: 'POST',
18695
+ body: { ...draft, apiKey: draft.apiKey || '' },
18696
+ parse: 'always',
18697
+ });
18698
+ const doc = (resp && resp.data) || {};
18699
+ if (doc.saved) {
18700
+ setNote({ ok: true, text: weT('已保存') });
18701
+ await load();
18702
+ const state = await apiJson('/pet-chat/state', { parse: 'always' });
18703
+ const sdoc = (state && state.data) || {};
18704
+ setStatus(sdoc.reachable
18705
+ ? { ok: true, text: weT('已连接 · {p} · {m}', { p: sdoc.provider || draft.provider, m: sdoc.model || draft.model }) }
18706
+ : { ok: false, text: sdoc.lastError ? weT('未连接:{e}', { e: sdoc.lastError }) : weT('已保存,但还没连上') });
18707
+ } else {
18708
+ setNote({ ok: false, text: weT('保存失败') });
18709
+ }
18710
+ } catch (e) {
18711
+ setNote({ ok: false, text: weT('保存失败:{msg}', { msg: (e && e.message) || '' }) });
18712
+ } finally { setBusy(false); }
18713
+ };
18714
+
18715
+ const testConnection = async () => {
18716
+ setBusy(true);
18717
+ try {
18718
+ const resp = await apiJson('/pet-chat/test', {
18719
+ method: 'POST',
18720
+ body: { provider: draft.provider, baseUrl: draft.baseUrl, apiKey: draft.apiKey || '' },
18721
+ parse: 'always',
18722
+ });
18723
+ const doc = (resp && resp.data) || {};
18724
+ setStatus(doc.ok
18725
+ ? { ok: true, text: weT('已连接 · {p}', { p: doc.provider || draft.provider }) }
18726
+ : { ok: false, text: doc.message || weT('连接失败') });
18727
+ } catch (e) {
18728
+ setStatus({ ok: false, text: weT('连接失败:{msg}', { msg: (e && e.message) || '' }) });
18729
+ } finally { setBusy(false); }
18730
+ };
18731
+
18732
+ const switchProvider = (provider) => {
18733
+ const preset = PROVIDER_PRESETS[provider] || PROVIDER_PRESETS.openai;
18734
+ update({ provider, baseUrl: preset.baseUrl, model: preset.model, ...(provider === 'ollama' ? { apiKey: '' } : {}) });
18735
+ };
18736
+
18737
+ const voices = (() => {
18738
+ try {
18739
+ const list = typeof window !== 'undefined' && window.speechSynthesis && window.speechSynthesis.getVoices
18740
+ ? window.speechSynthesis.getVoices() : [];
18741
+ return Array.isArray(list) ? list : [];
18742
+ } catch { return []; }
18743
+ })();
18744
+
18745
+ const row = (label, node) => React.createElement('label', { key: label, style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
18746
+ weT(label), node);
18747
+
18748
+ const child = [];
18749
+ child.push(React.createElement('div', { key: 'title', style: { fontWeight: 600, margin: '14px 0 6px', fontSize: '13px' } }, weT('桌宠对话')));
18750
+ child.push(row('开启对话', React.createElement('input', {
18751
+ type: 'checkbox', checked: Boolean(draft.enabled), disabled: busy,
18752
+ onChange: (e) => update({ enabled: e.target.checked }),
18753
+ })));
18754
+ child.push(row('模型来源', React.createElement('select', {
18755
+ value: draft.provider, disabled: busy,
18756
+ onChange: (e) => switchProvider(e.target.value),
18757
+ },
18758
+ React.createElement('option', { value: 'openai' }, 'OpenAI 兼容'),
18759
+ React.createElement('option', { value: 'ollama' }, weT('本机 Ollama')))));
18760
+ child.push(row('接口地址', React.createElement('input', {
18761
+ type: 'text', value: draft.baseUrl, disabled: busy || draft.provider === 'ollama',
18762
+ style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ baseUrl: e.target.value }),
18763
+ })));
18764
+ child.push(row('模型名', React.createElement('input', {
18765
+ type: 'text', value: draft.model, disabled: busy,
18766
+ style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ model: e.target.value }),
18767
+ })));
18768
+ child.push(React.createElement('div', { key: 'key', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
18769
+ weT('API Key'),
18770
+ React.createElement('input', {
18771
+ type: showKey ? 'text' : 'password',
18772
+ value: draft.apiKey || '',
18773
+ placeholder: draft.hasApiKey ? (draft.apiKeyMasked || '••••••••') : '',
18774
+ disabled: busy || draft.provider === 'ollama',
18775
+ style: { flex: 1, minWidth: 0 },
18776
+ onChange: (e) => update({ apiKey: e.target.value }),
18777
+ }),
18778
+ React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: () => setShowKey((v) => !v) }, showKey ? weT('隐藏') : weT('显示')),
18779
+ React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: testConnection }, weT('测试连接')),
18780
+ ));
18781
+
18782
+ child.push(React.createElement('div', { key: 'persona', style: { display: 'flex', gap: '6px', fontSize: '12px', margin: '4px 0', flexWrap: 'wrap' } },
18783
+ weT('人设'),
18784
+ React.createElement('input', { type: 'text', placeholder: weT('名字'), value: (draft.persona && draft.persona.name) || '', style: { width: '80px' }, disabled: busy, onChange: (e) => update({ persona: { ...draft.persona, name: e.target.value } }) }),
18785
+ React.createElement('input', { type: 'text', placeholder: weT('性格'), value: (draft.persona && draft.persona.traits) || '', style: { flex: 1, minWidth: '120px' }, disabled: busy, onChange: (e) => update({ persona: { ...draft.persona, traits: e.target.value } }) }),
18786
+ React.createElement('input', { type: 'text', placeholder: weT('备注'), value: (draft.persona && draft.persona.notes) || '', style: { flex: 1, minWidth: '120px' }, disabled: busy, onChange: (e) => update({ persona: { ...draft.persona, notes: e.target.value } }) }),
18787
+ ));
18788
+ child.push(React.createElement('div', { key: 'limits', style: { display: 'flex', gap: '8px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
18789
+ weT('上下文轮数'),
18790
+ React.createElement('input', { type: 'number', min: 1, max: 12, value: draft.maxTurns, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ maxTurns: Number(e.target.value) }) }),
18791
+ weT('字数上限'),
18792
+ React.createElement('input', { type: 'number', min: 20, max: 160, value: draft.maxChars, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ maxChars: Number(e.target.value) }) }),
18793
+ ));
18794
+
18795
+ child.push(React.createElement('div', { key: 'voice', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '6px 0 0', flexWrap: 'wrap' } },
18796
+ React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
18797
+ React.createElement('input', { type: 'checkbox', checked: Boolean(draft.voiceOut && draft.voiceOut.enabled), disabled: busy, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, enabled: e.target.checked } }) }),
18798
+ weT('朗读回答')),
18799
+ weT('音色'),
18800
+ React.createElement('select', {
18801
+ className: 'we-picker__playlist-select', value: (draft.voiceOut && draft.voiceOut.voiceURI) || '', disabled: busy,
18802
+ onChange: (e) => update({ voiceOut: { ...draft.voiceOut, voiceURI: e.target.value } }),
18803
+ }, React.createElement('option', { value: '' }, weT('自动(中文)')), voices.slice(0, 40).map((v) => React.createElement('option', { key: v.voiceURI, value: v.voiceURI }, v.name))),
18804
+ weT('语速'),
18805
+ React.createElement('input', { type: 'range', min: 0.5, max: 2, step: 0.1, value: (draft.voiceOut && draft.voiceOut.rate) || 1, disabled: busy, style: { width: '80px' }, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, rate: Number(e.target.value) } }) }),
18806
+ weT('音量'),
18807
+ React.createElement('input', { type: 'range', min: 0, max: 1, step: 0.1, value: (draft.voiceOut && draft.voiceOut.volume) || 1, disabled: busy, style: { width: '80px' }, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, volume: Number(e.target.value) } }) }),
18808
+ React.createElement('button', {
18809
+ type: 'button', className: 'we-picker__btn', disabled: busy,
18810
+ onClick: () => {
18811
+ try {
18812
+ const synth = window.speechSynthesis;
18813
+ if (!synth) { setNote({ ok: false, text: weT('这台机器没有系统语音') }); return; }
18814
+ synth.cancel();
18815
+ const utter = new window.SpeechSynthesisUtterance(weT('你好,我是你的桌宠。'));
18816
+ utter.rate = (draft.voiceOut && draft.voiceOut.rate) || 1;
18817
+ utter.volume = (draft.voiceOut && draft.voiceOut.volume) || 1;
18818
+ synth.speak(utter);
18819
+ } catch { setNote({ ok: false, text: weT('试听失败') }); }
18820
+ },
18821
+ }, weT('试听')),
18822
+ ));
18823
+
18824
+ child.push(row('朗读引擎', React.createElement('select', {
18825
+ value: draft.voiceEngine || 'system', disabled: busy,
18826
+ onChange: (e) => update({ voiceEngine: e.target.value }),
18827
+ },
18828
+ React.createElement('option', { value: 'system' }, weT('系统语音')),
18829
+ React.createElement('option', { value: 'edge' }, weT('在线情感 edge-tts')))));
18830
+
18831
+ child.push(React.createElement('div', { key: 'memory', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
18832
+ React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
18833
+ React.createElement('input', { type: 'checkbox', checked: draft.memoryEnabled !== false, disabled: busy, onChange: (e) => update({ memoryEnabled: e.target.checked }) }),
18834
+ weT('长期记忆')),
18835
+ React.createElement('button', {
18836
+ type: 'button', className: 'we-picker__btn', disabled: busy,
18837
+ onClick: async () => {
18838
+ try {
18839
+ const resp = await apiJson('/pet-chat/memory', { parse: 'always' });
18840
+ setMemory(((resp && resp.data) || {}).memory || {});
18841
+ } catch { setNote({ ok: false, text: weT('读取记忆失败') }); }
18842
+ },
18843
+ }, weT('查看记忆')),
18844
+ React.createElement('button', {
18845
+ type: 'button', className: 'we-picker__btn', disabled: busy,
18846
+ onClick: async () => {
18847
+ try {
18848
+ await apiJson('/pet-chat/memory', { method: 'DELETE', parse: 'always' });
18849
+ setMemory(null);
18850
+ setNote({ ok: true, text: weT('记忆已清空') });
18851
+ } catch { setNote({ ok: false, text: weT('清空失败') }); }
18852
+ },
18853
+ }, weT('清空记忆')),
18854
+ ));
18855
+ if (memory) {
18856
+ const parts = [];
18857
+ if (memory.nickname) parts.push(weT('称呼') + ':' + memory.nickname);
18858
+ if (Array.isArray(memory.likes) && memory.likes.length) parts.push(weT('喜欢') + ':' + memory.likes.join('、'));
18859
+ if (Array.isArray(memory.notes) && memory.notes.length) parts.push(weT('备注') + ':' + memory.notes.join('、'));
18860
+ child.push(React.createElement('div', { key: 'memoryView', className: 'we-picker__hint', style: { margin: '2px 0 6px' } }, parts.length ? parts.join(' · ') : weT('还没有记住任何偏好')));
18861
+ }
18862
+
18863
+ child.push(React.createElement('div', { key: 'proactive', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0', flexWrap: 'wrap' } },
18864
+ React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
18865
+ React.createElement('input', { type: 'checkbox', checked: Boolean(draft.proactive && draft.proactive.enabled), disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, enabled: e.target.checked } }) }),
18866
+ weT('主动闲聊')),
18867
+ weT('每日'),
18868
+ React.createElement('input', { type: 'number', min: 1, max: 20, value: (draft.proactive && draft.proactive.dailyLimit) || 10, style: { width: '56px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, dailyLimit: Number(e.target.value) } }) }),
18869
+ weT('间隔(分)'),
18870
+ React.createElement('input', { type: 'number', min: 30, max: 720, value: (draft.proactive && draft.proactive.minGapMin) || 120, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, minGapMin: Number(e.target.value) } }) }),
18871
+ weT('夜间静默'),
18872
+ React.createElement('input', { type: 'text', value: (draft.proactive && draft.proactive.quietHours) || '22:00-08:00', style: { width: '110px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, quietHours: e.target.value } }) }),
18873
+ ));
18874
+
18875
+ child.push(React.createElement('label', { key: 'asr', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0 8px', opacity: 0.7 } },
18876
+ React.createElement('input', { type: 'checkbox', checked: Boolean(draft.voiceEnabled), disabled: true }),
18877
+ weT('语音输入(需先在 DSH 开启)'),
18878
+ ));
18879
+
18880
+ child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '2px 0 6px', color: status.ok === false ? '#f87171' : undefined } },
18881
+ status.text || weT('未连接')));
18882
+ if (note && note.text) {
18883
+ child.push(React.createElement('div', { key: 'note', className: 'we-picker__hint', style: { color: note.ok ? undefined : '#f87171' } }, note.text));
18884
+ }
18885
+ child.push(React.createElement('div', { key: 'save', style: { display: 'flex', gap: '6px', marginTop: '4px' } },
18886
+ React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: save }, weT('保存')),
18887
+ ));
18888
+
18889
+ return React.createElement('div', { style: { ...PET_STYLE.card, marginTop: '10px' } }, child);
18890
+ }
18891
+
18638
18892
  /** 页签组装点调用它。 */
18639
18893
  function renderPetsTab() {
18640
18894
  return React.createElement(PetsTabPanel, null);
@@ -20657,6 +20911,9 @@ window.__ModuleLoader__.load({
20657
20911
  }
20658
20912
 
20659
20913
  function petChatShow() {
20914
+ // 「关闭对话」时点宠物**不弹气泡**(判据⑥):开关是显式 false 才拦,
20915
+ // 还没探测过(null)时照常打开 —— 首次点击要能触发一次 /state 探测。
20916
+ if (petChatVoiceOut && petChatChatEnabled === false) return;
20660
20917
  const els = petChatBuild();
20661
20918
  if (!els) return;
20662
20919
  els.root.style.display = 'flex';
@@ -20707,6 +20964,8 @@ window.__ModuleLoader__.load({
20707
20964
  const doc = probe && probe.data;
20708
20965
  // 语音输入开关由宿主带回来:false ⇒ 按麦克风只提示"先去 DSH 开",不弹权限框
20709
20966
  petChatVoiceEnabled = doc && doc.voiceEnabled === true;
20967
+ // 对话总开关:显式 false ⇒ 点宠物不弹气泡(判据⑥)
20968
+ petChatChatEnabled = Boolean(doc && doc.enabled === true);
20710
20969
  if (doc && doc.voiceOut && typeof doc.voiceOut === 'object') petChatVoiceOut = doc.voiceOut;
20711
20970
  if (!doc || doc.enabled !== true) {
20712
20971
  petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
@@ -20889,6 +21148,8 @@ window.__ModuleLoader__.load({
20889
21148
  const PET_CHAT_VOICE_MAX_SECONDS = 15;
20890
21149
  let petChatVoice = null;
20891
21150
  let petChatVoiceEnabled = null;
21151
+ // 对话总开关:/state 带回;显式 false 时点宠物不弹气泡(判据⑥)
21152
+ let petChatChatEnabled = null;
20892
21153
  // 朗读(TTS):默认开;配置由 /state 带回,没拿到时按默认值(开)
20893
21154
  /** 朗读入口:engine=edge 走宿主合成,其余(或失败)走系统音色。 */
20894
21155
  async function petChatSpeak(text, emotion) {
package/lib/index.js CHANGED
@@ -303,7 +303,11 @@ export function apply(ctx) {
303
303
  readSettings,
304
304
  // 语音输入:宿主自带的转写服务。用户没启用「语音输入」时这里是 undefined,
305
305
  // 路由据此回 asr-not-ready(不是启动失败)。
306
- speechToText: ctx.speechToText,
306
+ //
307
+ // **必须走 ctx.get()**:`speechToText` 不在本插件的 inject 里,直读 `ctx.speechToText`
308
+ // 会抛 "cannot get property … without inject",让整个插件加载失败(POSTMORTEM-LOAD-CRASH)。
309
+ // 静态扫描判据:test/verify-ctx-access.mjs;加载冒烟:test/verify-entry-load.mjs。
310
+ speechToText: typeof ctx.get === 'function' ? ctx.get('speechToText') : undefined,
307
311
  // edge-tts:默认用内置实现(生产),判据可注入假 transport
308
312
  edgeTts: undefined,
309
313
  });
@@ -25,6 +25,10 @@
25
25
  // `edgeTts`:在线情感朗读的合成函数(判据注入假 transport;生产为 undefined ⇒ 用默认实现)。
26
26
  export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText', 'edgeTts'];
27
27
 
28
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
29
+ import { homedir } from 'node:os';
30
+ import { dirname, join } from 'node:path';
31
+
28
32
  import {
29
33
  readMemory, writeMemory, clearMemory, parseExplicitMemory, rememberExplicit,
30
34
  mergeSummary, memoryPromptLine, MEMORY_SUMMARY_PROMPT,
@@ -114,7 +118,8 @@ export function decodeBase64(text) {
114
118
 
115
119
  /** 各 provider 的默认端点 / 默认模型(设置里 baseUrl / model 为空时用)。 */
116
120
  const PROVIDER_DEFAULTS = {
117
- ollama: { baseUrl: 'http://127.0.0.1:11434', model: 'qwen2.5:7b' },
121
+ // Ollama 的 OpenAI 兼容前缀是 /v1(少了它 /chat/completions 会 404)
122
+ ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'qwen2.5:7b' },
118
123
  openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
119
124
  };
120
125
 
@@ -260,6 +265,39 @@ export function registerPetChatRoutes(webServer, c) {
260
265
  /** 最近一次失败原因(`/state` 里回给界面)。 */
261
266
  let lastError = null;
262
267
 
268
+ /**
269
+ * 面板保存的覆盖层(`<DSH_FOLIA_HOME>/pet-chat/settings.json`)。
270
+ *
271
+ * 为什么不用 DSH 的设置服务:插件这边只拿到了 `readSettings`(只读),没有写入口;
272
+ * 桌宠面板又必须能改(开启对话 / 换模型 / 填 key 都在这里)。所以沿用 `/pets/config`
273
+ * 的做法,用一个插件自己的配置文件当**覆盖层**:
274
+ * · 读:schema 默认值 → DSH 设置 → 本文件(后者优先)
275
+ * · 写:只写本文件,不动 DSH 的设置档
276
+ * 好处是面板保存立刻生效、且插件卸载时删掉文件就回到 DSH 设置。
277
+ */
278
+ function overlayPath() {
279
+ const base = process.env.DSH_FOLIA_HOME || join(homedir(), '.dsh-folia');
280
+ return join(base, 'pet-chat', 'settings.json');
281
+ }
282
+
283
+ function readOverlay() {
284
+ try {
285
+ const file = overlayPath();
286
+ if (!existsSync(file)) return null;
287
+ const doc = JSON.parse(readFileSync(file, 'utf8'));
288
+ return doc && typeof doc === 'object' ? doc : null;
289
+ } catch { return null; }
290
+ }
291
+
292
+ function writeOverlay(patch) {
293
+ const file = overlayPath();
294
+ const current = readOverlay() || {};
295
+ const next = { ...current, ...patch };
296
+ mkdirSync(dirname(file), { recursive: true });
297
+ writeFileSync(file, JSON.stringify(next, null, 2));
298
+ return next;
299
+ }
300
+
263
301
  /** 读当前 petChat 配置(每次现读:设置面板改完立刻生效,不用重启)。 */
264
302
  function readPetChat() {
265
303
  let settings = null;
@@ -267,8 +305,9 @@ export function registerPetChatRoutes(webServer, c) {
267
305
  // 读设置失败不能让整条链路炸:当作默认(关)
268
306
  log('[pet-chat] 读设置失败:' + String((error && error.message) || error));
269
307
  }
270
- const raw = settings && typeof settings === 'object' && settings.petChat && typeof settings.petChat === 'object'
308
+ const schemaRaw = settings && typeof settings === 'object' && settings.petChat && typeof settings.petChat === 'object'
271
309
  ? settings.petChat : {};
310
+ const raw = { ...schemaRaw, ...(readOverlay() || {}) };
272
311
  const provider = raw.provider === 'openai' ? 'openai' : 'ollama';
273
312
  const defaults = PROVIDER_DEFAULTS[provider];
274
313
  const baseUrl = typeof raw.baseUrl === 'string' && raw.baseUrl.trim() ? raw.baseUrl.trim() : defaults.baseUrl;
@@ -708,6 +747,149 @@ export function registerPetChatRoutes(webServer, c) {
708
747
  /**
709
748
  * POST /pet-chat/speak —— **朗读**.的宿主侧。
710
749
  *
750
+ /**
751
+ * 设置面板用的读写接口。
752
+ *
753
+ * GET /pet-chat/config 回完整配置(apiKey 只回掩码 + hasApiKey)
754
+ * POST /pet-chat/config 保存(写覆盖层;provider=ollama 时强制默认地址、清空 key)
755
+ * POST /pet-chat/test 真连一次 provider,失败给具体原因(401/402/超时/地址错)
756
+ * DELETE /pet-chat/memory 只清记忆,不动对话与设置
757
+ */
758
+ async function handleConfigGet(res) {
759
+ const config = readPetChat();
760
+ const key = String(config.apiKey || '');
761
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
762
+ res.end(JSON.stringify({
763
+ ok: true,
764
+ data: {
765
+ enabled: config.enabled === true,
766
+ provider: config.provider,
767
+ baseUrl: config.baseUrl,
768
+ model: config.model,
769
+ apiKeyMasked: key ? `${key.slice(0, 3)}${'•'.repeat(Math.max(4, Math.min(16, key.length - 7)))}${key.slice(-4)}` : '',
770
+ hasApiKey: Boolean(key),
771
+ persona: config.persona || {},
772
+ maxTurns: config.maxTurns,
773
+ maxChars: config.maxChars,
774
+ voiceOut: config.voiceOut,
775
+ voiceEngine: config.voiceEngine,
776
+ memoryEnabled: config.memoryEnabled !== false,
777
+ proactive: {
778
+ enabled: config.proactiveEnabled === true,
779
+ dailyLimit: config.proactiveDailyLimit,
780
+ minGapMin: config.proactiveMinGapMin,
781
+ quietHours: config.quietHours || QUIET_HOURS_DEFAULT,
782
+ },
783
+ voiceEnabled: config.voiceEnabled === true,
784
+ },
785
+ }));
786
+ }
787
+
788
+ async function handleConfigPost(req, res) {
789
+ const send = (payload, status = 200) => {
790
+ res.statusCode = status;
791
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
792
+ res.end(JSON.stringify(payload));
793
+ };
794
+ let body = {};
795
+ try { body = await readJsonBody(req); } catch { send({ ok: false, error: 'bad-json' }, 400); return; }
796
+
797
+ const provider = body.provider === 'openai' ? 'openai' : 'ollama';
798
+ const defaults = PROVIDER_DEFAULTS[provider];
799
+ const patch = { provider };
800
+
801
+ if (typeof body.enabled === 'boolean') patch.enabled = body.enabled;
802
+ if (provider === 'ollama') {
803
+ // 本机 Ollama:地址固定默认、key 不用(避免 UI 上还留着上一家的 key)
804
+ patch.baseUrl = defaults.baseUrl;
805
+ patch.apiKey = '';
806
+ } else {
807
+ if (typeof body.baseUrl === 'string' && body.baseUrl.trim()) patch.baseUrl = body.baseUrl.trim().replace(/\/+$/, '');
808
+ if (typeof body.apiKey === 'string') patch.apiKey = body.apiKey.trim();
809
+ }
810
+ if (typeof body.model === 'string' && body.model.trim()) patch.model = body.model.trim();
811
+ if (body.persona && typeof body.persona === 'object') {
812
+ patch.persona = {
813
+ name: String(body.persona.name || '').slice(0, 24),
814
+ traits: String(body.persona.traits || '').slice(0, 200),
815
+ notes: String(body.persona.notes || '').slice(0, 200),
816
+ };
817
+ }
818
+ if (body.maxTurns != null) patch.maxTurns = Math.max(1, Math.min(12, Number(body.maxTurns) || 8));
819
+ if (body.maxChars != null) patch.maxChars = Math.max(20, Math.min(160, Number(body.maxChars) || 80));
820
+ if (body.voiceOut && typeof body.voiceOut === 'object') {
821
+ patch.voiceOut = {
822
+ enabled: body.voiceOut.enabled !== false,
823
+ rate: Math.max(0.5, Math.min(2, Number(body.voiceOut.rate) || 1)),
824
+ pitch: Math.max(0, Math.min(2, Number(body.voiceOut.pitch) || 1)),
825
+ volume: Math.max(0, Math.min(1, Number(body.voiceOut.volume) || 1)),
826
+ voiceURI: String(body.voiceOut.voiceURI || '').slice(0, 200),
827
+ };
828
+ }
829
+ if (body.voiceEngine === 'edge' || body.voiceEngine === 'system') patch.voiceEngine = body.voiceEngine;
830
+ if (typeof body.memoryEnabled === 'boolean') patch.memoryEnabled = body.memoryEnabled;
831
+ if (body.proactive && typeof body.proactive === 'object') {
832
+ patch.proactiveEnabled = body.proactive.enabled === true;
833
+ patch.proactiveDailyLimit = Math.max(1, Math.min(20, Number(body.proactive.dailyLimit) || 10));
834
+ patch.proactiveMinGapMin = Math.max(30, Math.min(720, Number(body.proactive.minGapMin) || 120));
835
+ if (typeof body.proactive.quietHours === 'string') patch.quietHours = body.proactive.quietHours;
836
+ }
837
+ if (typeof body.voiceEnabled === 'boolean') patch.voiceEnabled = body.voiceEnabled;
838
+
839
+ writeOverlay(patch);
840
+ const config = readPetChat();
841
+ send({
842
+ ok: true,
843
+ data: { saved: true, enabled: config.enabled, provider: config.provider, baseUrl: config.baseUrl, model: config.model },
844
+ });
845
+ }
846
+
847
+ /** 真连一次 provider:失败要说清是 401 / 402 / 超时 / 地址错。 */
848
+ async function handleConfigTest(req, res) {
849
+ const send = (payload, status = 200) => {
850
+ res.statusCode = status;
851
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
852
+ res.end(JSON.stringify(payload));
853
+ };
854
+ let body = {};
855
+ try { body = await readJsonBody(req); } catch { body = {}; }
856
+ const config = readPetChat();
857
+ const baseUrl = String(body.baseUrl || config.baseUrl || '').replace(/\/+$/, '');
858
+ const apiKey = typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : config.apiKey;
859
+ const provider = body.provider === 'openai' ? 'openai' : (body.provider === 'ollama' ? 'ollama' : config.provider);
860
+ if (!baseUrl) { send({ ok: false, code: 'no-base-url', message: '接口地址为空' }); return; }
861
+
862
+ const controller = new AbortController();
863
+ const timer = setTimeout(() => controller.abort(), 8000);
864
+ try {
865
+ const response = await fetch(`${baseUrl}/models`, {
866
+ headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},
867
+ signal: controller.signal,
868
+ });
869
+ if (response.status === 401 || response.status === 403) {
870
+ send({ ok: false, code: 'unauthorized', status: response.status, message: 'API Key 无效或没有权限(401)' });
871
+ return;
872
+ }
873
+ if (response.status === 402) { send({ ok: false, code: 'no-balance', status: 402, message: '账号余额不足(402)' }); return; }
874
+ if (!response.ok) {
875
+ send({ ok: false, code: 'http', status: response.status, message: `服务返回 ${response.status}` });
876
+ return;
877
+ }
878
+ send({ ok: true, provider, baseUrl, models: 'reachable' });
879
+ } catch (error) {
880
+ const aborted = controller.signal.aborted;
881
+ const message = String((error && error.message) || error);
882
+ send({
883
+ ok: false,
884
+ code: aborted ? 'timeout' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? 'dns' : 'network'),
885
+ message: aborted ? '连接超时(8 秒)' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? '地址解析失败,检查接口地址' : `网络错误:${message.slice(0, 80)}`),
886
+ });
887
+ } finally {
888
+ clearTimeout(timer);
889
+ }
890
+ }
891
+
892
+ /**
711
893
  * 两档引擎(工单阶段 2):
712
894
  * · `system`(默认):**不发任何网络请求**,只回 `{engine:'system'}`,客户端用系统音色读;
713
895
  * · `edge`:宿主去连微软的在线朗读,拿回 mp3 字节(base64)交给客户端播;
@@ -767,11 +949,14 @@ export function registerPetChatRoutes(webServer, c) {
767
949
  disposers.push(webServer.register({
768
950
  kind: 'prefix',
769
951
  path: `${BASE}/pet-chat`,
770
- handler: (req, res) => {
952
+ handler: async (req, res) => {
771
953
  const url = new URL(req.url || '/', 'http://x');
772
954
  const tail = url.pathname.slice(`${BASE}/pet-chat`.length).replace(/\/+$/, '');
773
955
  const method = (req.method || 'GET').toUpperCase();
774
956
  if (tail === '/state' && (method === 'GET' || method === 'HEAD')) { handleState(res); return; }
957
+ if (tail === '/config' && (method === 'GET' || method === 'HEAD')) { await handleConfigGet(res); return; }
958
+ if (tail === '/config' && method === 'POST') { await handleConfigPost(req, res); return; }
959
+ if (tail === '/test' && method === 'POST') { await handleConfigTest(req, res); return; }
775
960
  if (tail === '/models' && (method === 'GET' || method === 'HEAD')) { handleModels(res); return; }
776
961
  if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
777
962
  if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
@@ -791,6 +976,13 @@ export function registerPetChatRoutes(webServer, c) {
791
976
  res.end(JSON.stringify({ ok: true, memory, line, enabled: readPetChat().memoryEnabled !== false }));
792
977
  return;
793
978
  }
979
+ if (tail === '/memory' && method === 'DELETE') {
980
+ // 面板的「清空记忆」:只清偏好记忆,不动对话历史、不动设置
981
+ clearMemory();
982
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
983
+ res.end(JSON.stringify({ ok: true, cleared: true }));
984
+ return;
985
+ }
794
986
  if (tail === '/proactive/tick' && method === 'POST') { handleProactiveTick(req, res); return; }
795
987
  if (tail === '/proactive/skip' && method === 'POST') { handleReset2(res); return; }
796
988
  res.statusCode = 404;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.26.0-pre.3",
3
+ "version": "4.26.0-pre.6",
4
4
  "description": "DSH 壁纸引擎:本机 WE 壁纸实时渲染,视频/网页/开机动画/桌宠皮肤,一键拉取在线素材。",
5
5
  "type": "module",
6
6
  "engines": {