dsh-folia 1.1.0 → 1.3.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.
@@ -30,7 +30,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,
30
30
  import { homedir, tmpdir } from 'node:os';
31
31
  import { dirname, join } from 'node:path';
32
32
  import { spawn } from 'node:child_process';
33
- import { createTtsService, normalizeTtsText, TTS_MAX_CHARS, TTS_ENGINES } from '../tts/tts.js';
33
+ import { createTtsService, normalizeTtsText, sanitizeLyrics, TTS_MAX_CHARS, TTS_ENGINES } from '../tts/tts.js';
34
34
  import { planSing, tuneSources, TUNE_LIBRARY } from '../tts/singing.js';
35
35
  import { synthesizeSong } from '../tts/sing-synth.js';
36
36
  import { TTS_CATALOG, piperAssetUrls, piperModelUrls } from '../tts/catalog.js';
@@ -41,6 +41,10 @@ import {
41
41
  readVoiceCenter, publicVoiceCenter, volcHostConfig, saveVolcConfig, markVolcTest, setPreferredVoice,
42
42
  setDefaultPack, voiceEngineOf, resolvePersonaVoice, normalizeVoiceId, VOLC_VOICE_SUGGESTIONS,
43
43
  } from '../tts/voice-center.js';
44
+ // v1.2:用户音色包导入 + 4 个内置系统音效(不携带任何角色/声优素材)
45
+ import {
46
+ voicePackSummary, importVoicePack, removeUserVoicePack, listSystemSounds, SYSTEM_SOUNDS,
47
+ } from '../tts/voice-pack.js';
44
48
  import { appendToolLog } from '../persona-tool-log.js';
45
49
  import { CAPABILITIES } from '../capabilities-catalog.js';
46
50
  import { CURATED_BUNDLES } from '../capabilities-curated.js';
@@ -53,6 +57,7 @@ import {
53
57
  timeAnswer, dateAnswer, isConfirmText, isCancelText, isKnownTool, toolNeedsConfirm,
54
58
  buildCapabilityPrompt, capabilityForText, localCapabilityAnswer, thinkingTier,
55
59
  buildSelfCheckPrompt, reasonerModelFor, buildTaskPlan, taskPlanSentence,
60
+ detectCrisis, treeholeSafetyReply, resolveTurnPolicy,
56
61
  } from '../pet-chat-brain.js';
57
62
  import {
58
63
  runTool, readPetConfig, dueReminders, markReminderFired,
@@ -64,7 +69,10 @@ import {
64
69
  } from '../persona-store.js';
65
70
  import {
66
71
  appendEvent, retrieveEvents, listEvents, writeSummary, clearEvents,
72
+ recordObservation, listObservations, clearObservations, memoryStats, memoryBackend,
73
+ deleteEventsByDate, rollbackEvents, decayTick, memoryMigrationInfo, memoryStoragePath,
67
74
  } from '../persona-memory.js';
75
+ import { touchRelations, relationsPromptLine, lorePromptLine } from '../memory-db.js';
68
76
  import { reflectGrowth, REFLECT_EVERY_TURNS } from '../persona-growth.js';
69
77
  import { createPersonaApi } from './personas.js';
70
78
  // v0.1:旧键迁移与默认值只在 settings-schema 定义一次,路由复用同一个函数
@@ -81,6 +89,14 @@ import {
81
89
  enterSilence, clearSilence, parseSilenceCommand, PROACTIVE_RULES,
82
90
  canEventSpeak, buildEventLine, markEventSaid, EVENT_RULES,
83
91
  } from '../pet-chat-proactive.js';
92
+ // v1.2:主动思维(内心 tick)+ 屏幕感知(前台窗口 / OCR)
93
+ import {
94
+ mindTick, markMindSaid, markMindTick, readMindState, clearMindState, MIND_RULES,
95
+ } from '../pet-chat-mind.js';
96
+ import {
97
+ readForegroundWindow, captureScreenOcr, foregroundObservation, ocrObservation,
98
+ isSensitiveApp, isLockScreen, OBSERVE_RULES,
99
+ } from '../desktop-context.js';
84
100
 
85
101
  /** 单次输入上限(工单:≤400 字)。 */
86
102
  const MAX_INPUT_CHARS = 400;
@@ -663,6 +679,12 @@ export function registerPetChatRoutes(webServer, c) {
663
679
  wake: normalized.wake,
664
680
  // 记忆常开(零配置):设置里没有开关
665
681
  memoryEnabled: true,
682
+ // v1.2:会话模式 / 语音长度 / 主动思维 / 屏幕感知 / 树洞热线
683
+ conversationMode: normalized.conversationMode,
684
+ voiceLength: normalized.voiceLength,
685
+ proactive: normalized.proactive,
686
+ screen: normalized.screen,
687
+ treehole: normalized.treehole,
666
688
  // 实现细节:不再暴露给用户,也不再从设置里读
667
689
  maxTurns: DEFAULT_MAX_TURNS,
668
690
  maxChars: DEFAULT_MAX_CHARS,
@@ -697,6 +719,9 @@ export function registerPetChatRoutes(webServer, c) {
697
719
  return personaHistory.get(id);
698
720
  }
699
721
 
722
+ /** v1.3:上一段故事正文(内存,仅用于“继续讲/后来呢”;不落盘、不持久化)。 */
723
+ const lastStoryByPersona = new Map();
724
+
700
725
  /** 任务 §3⑤:最近几句回答(只用于「别重复同一句安慰话术」,不进历史)。 */
701
726
  const personaRecentReplies = new Map();
702
727
  /** v5 §3:多步任务的计划(进程内;重启清空,符合"这次会话里办完")。 */
@@ -749,6 +774,14 @@ export function registerPetChatRoutes(webServer, c) {
749
774
  try { appendEvent(persona.id, event); } catch { /* 记忆写失败不影响回复 */ }
750
775
  }
751
776
 
777
+ /** v1.3:静音指令只切 TTS 开关(字幕继续),不进入任何“模式”。 */
778
+ function setTtsMuted(muted) {
779
+ try {
780
+ const current = readVoiceRaw();
781
+ writeOverlay({ voice: { ...current, muted: muted === true } });
782
+ } catch { /* 写失败也不能拦住对话 */ }
783
+ }
784
+
752
785
  /** 非流式 JSON 调用(反思/摘要/两步策划共用;不写日志、不泄漏 Key)。 */
753
786
  async function callPersonaJson(config, system, user, maxTokens = 500, timeoutMs = 15000) {
754
787
  const controller = new AbortController();
@@ -805,13 +838,25 @@ export function registerPetChatRoutes(webServer, c) {
805
838
  * pre.65:system 由 core/growth/express/affect/世界书/召回记忆组成,不再读旧 memory.json。
806
839
  */
807
840
  function buildRequest(config, text, context = {}, persona = null) {
808
- const system = persona
841
+ // v1.2:关系/好感度 + 世界书 RAG(lore)都只作背景注入,不整本塞 prompt。
842
+ let memoryExtras = '';
843
+ if (persona) {
844
+ try {
845
+ const relations = relationsPromptLine(persona.id);
846
+ if (relations) memoryExtras += '\n' + relations;
847
+ } catch { /* ignore */ }
848
+ try { const lore = lorePromptLine(persona.id, text); if (lore) memoryExtras += '\n' + lore; } catch { /* ignore */ }
849
+ }
850
+ const baseSystem = persona
809
851
  ? buildPersonaSystemPrompt(persona, {
810
852
  env: context.env || '',
811
853
  mood: context.mood || null,
812
854
  memories: context.memories || [],
813
855
  userText: text,
814
856
  inputMode: context.inputMode,
857
+ turnPolicy: context.turnPolicy,
858
+ storyContext: context.storyContext,
859
+ voiceLength: context.voiceLength,
815
860
  // 任务 §3:内心步骤 / 先想过的要点 / 别重复的安慰话(都只进 system,不进历史)
816
861
  innerStep: context.innerStep || '',
817
862
  outline: context.outline || '',
@@ -819,9 +864,11 @@ export function registerPetChatRoutes(webServer, c) {
819
864
  affect: persona.affect,
820
865
  }) + '\n' + buildCapabilityPrompt()
821
866
  : buildSystemPrompt(config, {}, context.env || '', context.mood || null) + '\n' + buildCapabilityPrompt();
867
+ const system = baseSystem + memoryExtras;
822
868
  const headers = { 'content-type': 'application/json' };
823
869
  const history = persona ? historyFor(persona.id).slice(-config.maxTurns) : [];
824
870
  const temperature = Number(config.temperature);
871
+ const maxTokens = Math.max(0, Math.min(8192, Number(context.maxTokens) || 0));
825
872
  if (config.provider === 'openai') {
826
873
  if (config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
827
874
  return {
@@ -831,6 +878,7 @@ export function registerPetChatRoutes(webServer, c) {
831
878
  stream: true,
832
879
  temperature: Number.isFinite(temperature) ? temperature : 0.8,
833
880
  messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
881
+ ...(maxTokens ? { max_tokens: maxTokens } : {}),
834
882
  },
835
883
  headers,
836
884
  };
@@ -842,6 +890,7 @@ export function registerPetChatRoutes(webServer, c) {
842
890
  stream: true,
843
891
  temperature: Number.isFinite(temperature) ? temperature : 0.8,
844
892
  messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
893
+ ...(maxTokens ? { options: { num_predict: maxTokens } } : {}),
845
894
  },
846
895
  headers,
847
896
  };
@@ -899,6 +948,12 @@ export function registerPetChatRoutes(webServer, c) {
899
948
  voice,
900
949
  resolvedVoice,
901
950
  memoryEnabled: true,
951
+ // v1.3:模式已删除;“policy”由每轮 meta 下发,这里只保留字段兼容(恒 auto)。
952
+ conversationMode: 'auto',
953
+ voiceLength: config.voiceLength,
954
+ proactive: config.proactive,
955
+ screen: config.screen,
956
+ observing: config.screen.mode !== 'off',
902
957
  asrProvider: ASR_PROVIDER_ID,
903
958
  personas: persona ? {
904
959
  id: persona.id, name: persona.name, type: persona.type, mode: persona.mode,
@@ -1697,15 +1752,17 @@ export function registerPetChatRoutes(webServer, c) {
1697
1752
  const command = parseSilenceCommand(text);
1698
1753
  if (command === 'silence') {
1699
1754
  enterSilence();
1755
+ setTtsMuted(true);
1700
1756
  sse(res, 'delta', { t: '好,那我安静一会儿。' });
1701
- sse(res, 'done', { emotion: 'calm', command: 'silence', personaId: persona.id });
1757
+ sse(res, 'done', { emotion: 'calm', command: 'silence', muted: true, personaId: persona.id });
1702
1758
  res.end();
1703
1759
  return;
1704
1760
  }
1705
1761
  if (command === 'resume') {
1706
1762
  clearSilence();
1763
+ setTtsMuted(false);
1707
1764
  sse(res, 'delta', { t: '好,我回来了。' });
1708
- sse(res, 'done', { emotion: 'happy', command: 'resume', personaId: persona.id });
1765
+ sse(res, 'done', { emotion: 'happy', command: 'resume', muted: false, personaId: persona.id });
1709
1766
  res.end();
1710
1767
  return;
1711
1768
  }
@@ -1717,6 +1774,35 @@ export function registerPetChatRoutes(webServer, c) {
1717
1774
 
1718
1775
  const mood = detectMood(text, now);
1719
1776
  const inputMode = body.inputMode === 'voice' ? 'voice' : 'text';
1777
+ /**
1778
+ * v1.3:**每轮意图判定**(不持久化、没有“模式”)。
1779
+ * story / empathy 只看这一句话 + 上一轮是不是故事;旧字段 conversationMode 一律忽略。
1780
+ */
1781
+ const turnInfo = resolveTurnPolicy(text, { lastWasStory: lastStoryByPersona.has(persona.id) });
1782
+ const turnPolicy = turnInfo.policy;
1783
+ const storyContext = turnPolicy === 'story' && turnInfo.storyContinue
1784
+ ? String(lastStoryByPersona.get(persona.id) || '')
1785
+ : '';
1786
+
1787
+ /* ── 情绪/危机:命中自伤词先用固定回应接住,不交给模型自由发挥 ── */
1788
+ if (turnPolicy === 'empathy') {
1789
+ const hit = detectCrisis(text);
1790
+ if (hit) {
1791
+ const safety = treeholeSafetyReply((config.treehole && config.treehole.hotline) || '12356');
1792
+ recordPersonaEvent(persona, {
1793
+ kind: 'treehole', importance: 8,
1794
+ text: `情绪·危机词(${hit}):用户需要安全支持`,
1795
+ });
1796
+ sse(res, 'meta', { mood: mood.mood, rate: mood.rate, policy: 'empathy', safety: true });
1797
+ sse(res, 'delta', { t: safety });
1798
+ sse(res, 'done', {
1799
+ emotion: 'calm', safety: true, crisis: hit, policy: 'empathy', personaId: persona.id,
1800
+ mood: mood.mood, rate: mood.rate,
1801
+ });
1802
+ res.end();
1803
+ return;
1804
+ }
1805
+ }
1720
1806
 
1721
1807
  /**
1722
1808
  * 权限确认:**只有下一句是确认才执行**。
@@ -1754,6 +1840,10 @@ export function registerPetChatRoutes(webServer, c) {
1754
1840
  }
1755
1841
 
1756
1842
  let intent = classifyIntent(text, { now });
1843
+ // v1.3:故事 / 情绪轮不抢工具动作(“继续讲”“今天好累”都按对话处理)。
1844
+ if (turnPolicy !== 'chat') {
1845
+ intent = { intent: 'chat', tool: null, args: {}, confidence: 'rule', reason: 'turn-policy' };
1846
+ }
1757
1847
 
1758
1848
  // 特殊人设:任何系统动作都明确拒绝(不执行、不弹确认、不调工具)。
1759
1849
  if (!personaToolAllowed(persona) && intent.intent === 'action') {
@@ -1983,6 +2073,8 @@ export function registerPetChatRoutes(webServer, c) {
1983
2073
  : [];
1984
2074
  const request = buildRequest(config, text, {
1985
2075
  env, mood, memories: recalled.items, inputMode, innerStep: inner.text, outline, avoidLines,
2076
+ turnPolicy, storyContext, voiceLength: config.voiceLength,
2077
+ maxTokens: turnPolicy === 'story' ? 6000 : 0,
1986
2078
  }, persona);
1987
2079
  // v5 §5:三档思考(语音/寒暄 quick;文字复杂 standard;分析/规划/写作 deep)。
1988
2080
  const tier = thinkingTier(text, { inputMode });
@@ -2003,6 +2095,9 @@ export function registerPetChatRoutes(webServer, c) {
2003
2095
  emotion, usage: usage || null, intent: intent.intent, tier,
2004
2096
  mood: mood.mood, rate: mood.rate, personaId: persona.id, personaType: persona.type,
2005
2097
  memories: recalled.items.length, memoryTokens: recalled.tokens,
2098
+ policy: turnPolicy, conversationMode: 'auto', voiceLength: config.voiceLength,
2099
+ ...(turnPolicy === 'story' ? { story: true, storyContinue: turnInfo.storyContinue === true } : {}),
2100
+ ...(turnPolicy === 'empathy' ? { empathy: true } : {}),
2006
2101
  });
2007
2102
  res.end();
2008
2103
  };
@@ -2011,7 +2106,7 @@ export function registerPetChatRoutes(webServer, c) {
2011
2106
  * 深度档(仅文字;语音永远 quick):要点 → 草稿 → 自检 → 最终。
2012
2107
  * 可切 deepseek-reasoner(`reasonerModelFor`);>12s 直接降级用草稿,不让用户干等。
2013
2108
  */
2014
- if (tier === 'deep' && !teachConcept) {
2109
+ if (tier === 'deep' && !teachConcept && turnPolicy === 'chat') {
2015
2110
  const deepStart = Date.now();
2016
2111
  const deepConfig = { ...config, model: reasonerModelFor(config.model, tier) };
2017
2112
  let draft = '';
@@ -2034,6 +2129,7 @@ export function registerPetChatRoutes(webServer, c) {
2034
2129
  sse(res, 'meta', {
2035
2130
  mood: mood.mood, rate: mood.rate, intent: intent.intent, tier: 'deep',
2036
2131
  capability: capability ? capability.id : undefined, personaId: persona.id,
2132
+ policy: turnPolicy,
2037
2133
  deep: { model: deepConfig.model, selfCheck: true, ms: Date.now() - deepStart },
2038
2134
  });
2039
2135
  // 分块发出去,前端仍是逐字出现(不是一次性大段)。
@@ -2057,6 +2153,7 @@ export function registerPetChatRoutes(webServer, c) {
2057
2153
  sse(res, 'meta', {
2058
2154
  mood: mood.mood, rate: mood.rate, intent: intent.intent, tier,
2059
2155
  capability: capability ? capability.id : undefined, personaId: persona.id,
2156
+ policy: turnPolicy, ...(turnInfo.storyContinue ? { storyContinue: true } : {}),
2060
2157
  });
2061
2158
 
2062
2159
  try {
@@ -2075,8 +2172,16 @@ export function registerPetChatRoutes(webServer, c) {
2075
2172
  const decoder = new TextDecoder();
2076
2173
  let buffer = '';
2077
2174
  let full = '';
2078
- // 兼容老判据:不带 inputMode 的请求仍按旧 maxChars 截断;前端/新判据显式带 text/voice。
2079
- const legacyLimit = body.inputMode ? 0 : (Number(config.legacyMaxChars) || 80);
2175
+ // 兼容老判据:不带 inputMode 的请求仍按旧 maxChars 截断;故事轮永不截断。
2176
+ const legacyLimit = body.inputMode || turnPolicy === 'story' ? 0 : (Number(config.legacyMaxChars) || 80);
2177
+ /**
2178
+ * v1.3 语音回答长度:**只在 chat 轮**按句数限制(3/8/不限,默认 8)。
2179
+ * story / empathy 不限制(讲故事必须完整到结尾;共情允许短句但也可能多说两句)。
2180
+ * 到上限后**不 cancel 流**:模型继续生成、历史保留完整,只是不再往气泡推 delta。
2181
+ */
2182
+ const voiceLimit = turnPolicy === 'chat' && inputMode === 'voice'
2183
+ ? Math.max(0, Number(config.voiceLength) || 0) : 0;
2184
+ let voiceLimitReached = false;
2080
2185
  let stopped = false;
2081
2186
  const appendPiece = (piece) => {
2082
2187
  let chunk = String(piece || '');
@@ -2086,23 +2191,31 @@ export function registerPetChatRoutes(webServer, c) {
2086
2191
  if (room <= 0) return false;
2087
2192
  if (chunk.length > room) chunk = chunk.slice(0, room);
2088
2193
  }
2089
- if (inputMode === 'voice') {
2090
- // 语音模式:最多 3 句;到第 3 个句末就停(不再把第 4 句推给 TTS)。
2194
+ if (voiceLimit > 0) {
2195
+ const combined = full + chunk;
2196
+ if (voiceLimitReached) {
2197
+ full = combined;
2198
+ return true;
2199
+ }
2091
2200
  let sentences = 0;
2092
2201
  let cut = -1;
2093
- const combined = full + chunk;
2094
2202
  for (let i = 0; i < combined.length; i += 1) {
2095
2203
  if (/[。!?!?]/.test(combined[i])) {
2096
2204
  sentences += 1;
2097
- if (sentences >= 3) { cut = i + 1; break; }
2205
+ if (sentences >= voiceLimit) { cut = i + 1; break; }
2098
2206
  }
2099
2207
  }
2100
- if (cut >= 0) {
2101
- chunk = combined.slice(0, cut);
2102
- full = chunk;
2103
- sse(res, 'delta', { t: chunk });
2104
- return false;
2208
+ if (cut >= 0 && cut < combined.length) {
2209
+ const visible = combined.slice(full.length, cut);
2210
+ full = combined;
2211
+ voiceLimitReached = true;
2212
+ if (visible) sse(res, 'delta', { t: visible });
2213
+ return true;
2105
2214
  }
2215
+ full = combined;
2216
+ sse(res, 'delta', { t: chunk });
2217
+ if (cut === combined.length) voiceLimitReached = true;
2218
+ return true;
2106
2219
  }
2107
2220
  full += chunk;
2108
2221
  sse(res, 'delta', { t: chunk });
@@ -2133,6 +2246,19 @@ export function registerPetChatRoutes(webServer, c) {
2133
2246
  pushRecentReply(persona.id, parsed.reply);
2134
2247
  recordPersonaEvent(persona, { kind: 'chat', importance: 4, text: `用户:${text.slice(0, 500)}` });
2135
2248
  recordPersonaEvent(persona, { kind: 'chat', importance: 5, text: `我:${parsed.reply.slice(0, 1000)}` });
2249
+ // v1.3:故事轮记住上一段正文(内存,供“继续讲”衔接;不落盘)。
2250
+ if (turnPolicy === 'story' && parsed.reply) {
2251
+ lastStoryByPersona.set(persona.id, String(parsed.reply).slice(-3000));
2252
+ }
2253
+ // v1.3:情绪轮记住“在意的事/情绪触发点”(importance 6–8),但**不持久化任何模式**。
2254
+ if (turnPolicy === 'empathy') {
2255
+ recordPersonaEvent(persona, {
2256
+ kind: 'treehole', importance: 7,
2257
+ text: `情绪:用户说「${text.slice(0, 200)}」(先接情绪,不急着建议)`,
2258
+ });
2259
+ }
2260
+ // v1.2:从对话里抽实体写关系/好感度(保守规则,见 memory-db.extractEntities)。
2261
+ try { touchRelations(persona.id, text); } catch { /* 关系抽取失败不影响回复 */ }
2136
2262
  maybeReflect(persona, config);
2137
2263
  done(emotion, { chars: parsed.reply.length });
2138
2264
  } catch (error) {
@@ -2657,6 +2783,12 @@ const roots = [
2657
2783
  ownerName: config.ownerName,
2658
2784
  voice: publicVoice(readVoiceRaw()),
2659
2785
  wake: config.wake,
2786
+ // v1.2
2787
+ conversationMode: 'auto',
2788
+ voiceLength: config.voiceLength,
2789
+ proactive: config.proactive,
2790
+ screen: config.screen,
2791
+ treehole: config.treehole,
2660
2792
  },
2661
2793
  }));
2662
2794
  }
@@ -2709,6 +2841,39 @@ const roots = [
2709
2841
  };
2710
2842
  }
2711
2843
 
2844
+ /* ── v1.2 会话模式 / 语音长度 / 主动思维 / 屏幕感知 / 树洞 ───────────── */
2845
+ // v1.3:不再接受“会话模式”写入(旧字段保留在设置里仅为兼容,运行时忽略)。
2846
+ if ([0, 3, 8].includes(Number(body.voiceLength))) patch.voiceLength = Number(body.voiceLength);
2847
+ if (body.proactive && typeof body.proactive === 'object') {
2848
+ const previous = current.proactive || {};
2849
+ const interval = [0, 15, 30, 60].includes(Number(body.proactive.intervalMin))
2850
+ ? Number(body.proactive.intervalMin) : previous.intervalMin;
2851
+ const clock = (value, fallback) => (/^([01]\d|2[0-3]):[0-5]\d$/.test(String(value || '')) ? String(value) : fallback);
2852
+ patch.proactive = {
2853
+ enabled: body.proactive.enabled === true && interval !== 0,
2854
+ intervalMin: interval,
2855
+ quietFrom: clock(body.proactive.quietFrom, previous.quietFrom),
2856
+ quietTo: clock(body.proactive.quietTo, previous.quietTo),
2857
+ };
2858
+ }
2859
+ if (body.screen && typeof body.screen === 'object') {
2860
+ const previous = current.screen || { mode: 'off', confirmed: false };
2861
+ const mode = ['off', 'app', 'ocr'].includes(body.screen.mode) ? body.screen.mode : previous.mode;
2862
+ // 从 off 打开任何一级都要**二次确认**(UI 弹说明后带 confirm:true 再来一次);
2863
+ // 单纯把 confirmed 置 true 但不改 mode 不允许,避免“绕过说明直接开”。
2864
+ if (mode !== 'off' && previous.mode === 'off' && body.screen.confirm !== true) {
2865
+ send({ ok: false, code: 'screen-confirm-required', hint: '开启屏幕感知前需要先看说明并二次确认' }, 409);
2866
+ return;
2867
+ }
2868
+ patch.screen = { mode, confirmed: mode === 'off' ? false : (body.screen.confirm === true || previous.confirmed === true) };
2869
+ }
2870
+ if (body.treehole && typeof body.treehole === 'object') {
2871
+ patch.treehole = {
2872
+ hotline: typeof body.treehole.hotline === 'string' && body.treehole.hotline.trim()
2873
+ ? body.treehole.hotline.trim().slice(0, 40) : (current.treehole || {}).hotline || '12356',
2874
+ };
2875
+ }
2876
+
2712
2877
  writeOverlay(patch);
2713
2878
  const config = readPetChat();
2714
2879
  send({
@@ -2803,6 +2968,7 @@ const roots = [
2803
2968
  }));
2804
2969
  return;
2805
2970
  }
2971
+ const config = readPetChat();
2806
2972
  const decision = canSpeak({
2807
2973
  idleMinutes: Number(body.idleMinutes) || 0,
2808
2974
  fullscreen: body.fullscreen === true,
@@ -2810,6 +2976,13 @@ const roots = [
2810
2976
  now,
2811
2977
  });
2812
2978
  let line = null;
2979
+ // v1.2:主动搭话默认关。静默(用户说过“别说了”)优先于“默认关”,
2980
+ // 这样排障时能明确区分 “silent” 与 “disabled”。
2981
+ if (!decision.ok && decision.reason !== 'silent' && config.proactive.enabled !== true) {
2982
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
2983
+ res.end(JSON.stringify({ ok: false, reason: 'disabled', line: null, usage: todayUsage(now), enabled: false }));
2984
+ return;
2985
+ }
2813
2986
  if (decision.ok) {
2814
2987
  const state = readProactiveState(now);
2815
2988
  const active = getActivePersona();
@@ -2826,6 +2999,180 @@ const roots = [
2826
2999
  res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage(now) }));
2827
3000
  }
2828
3001
 
3002
+ /* ── v1.2 主动思维(内心 tick)────────────────────────────────────────── */
3003
+
3004
+ /**
3005
+ * 一次内心 tick:先过设置/勿扰/忙碌/静默闸门,再让 pet-chat-mind 决策。
3006
+ * 与 `/proactive/tick` 的区别:这是**没有外部事件**时的主动思考(默认关)。
3007
+ */
3008
+ async function handleMindTick(req, res) {
3009
+ let body = {};
3010
+ try { body = await readJsonBody(req); } catch { body = {}; }
3011
+ const send = (payload, status = 200) => {
3012
+ res.statusCode = status;
3013
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
3014
+ res.end(JSON.stringify(payload));
3015
+ };
3016
+ const config = readPetChat();
3017
+ const now = nowMs();
3018
+ const persona = getActivePersona();
3019
+ // 静默口令优先于“默认关”:用户说过“别说了”,任何 tick 都回 silent。
3020
+ if (isSilent(now)) {
3021
+ send({ ok: false, reason: 'silent', action: 'none', line: '', enabled: config.proactive.enabled });
3022
+ return;
3023
+ }
3024
+ if (config.proactive.enabled !== true) {
3025
+ send({ ok: false, reason: 'disabled', action: 'none', line: '', enabled: false });
3026
+ return;
3027
+ }
3028
+ let foreground = null;
3029
+ if (config.screen.mode !== 'off') {
3030
+ try { foreground = await readForegroundWindow(); } catch { foreground = null; }
3031
+ if (foreground && (foreground.locked || foreground.sensitive)) foreground = null;
3032
+ }
3033
+ const memories = persona ? retrieveEvents(persona.id, '', { topK: 3, tokenBudget: 300 }).items : [];
3034
+ const decision = mindTick({
3035
+ now,
3036
+ enabled: true,
3037
+ intervalMin: config.proactive.intervalMin,
3038
+ quietFrom: config.proactive.quietFrom,
3039
+ quietTo: config.proactive.quietTo,
3040
+ speaking: body.speaking === true,
3041
+ listening: body.listening === true,
3042
+ turnBusy: body.turnBusy === true,
3043
+ muted: Boolean(config.voice && config.voice.muted),
3044
+ silent: isSilent(now),
3045
+ activeMinutes: Number(body.activeMinutes) || 0,
3046
+ app: foreground ? foreground.app : '',
3047
+ title: foreground ? foreground.title : '',
3048
+ wallpaperTitle: body.wallpaperTitle,
3049
+ memories,
3050
+ observationText: body.observationText,
3051
+ state: readMindState(now),
3052
+ });
3053
+ if ((decision.action === 'speak' || decision.action === 'ask') && decision.line) {
3054
+ markMindSaid(now, decision.line, decision.kind);
3055
+ if (persona) {
3056
+ recordPersonaEvent(persona, { kind: 'event', importance: 3, text: `我主动搭话:${decision.line.slice(0, 200)}` });
3057
+ }
3058
+ // 只有真的“过闸并落地”才记账:被勿扰/静默挡下的 tick 不该吃掉 15 分钟间隔。
3059
+ markMindTick(now);
3060
+ } else if (decision.action === 'record') {
3061
+ if (body.observationText && persona) {
3062
+ recordObservation(persona.id, { text: String(body.observationText).slice(0, 200), importance: 2, source: 'mind' });
3063
+ }
3064
+ markMindTick(now);
3065
+ }
3066
+ send({
3067
+ ok: decision.action === 'speak' || decision.action === 'ask',
3068
+ ...decision,
3069
+ enabled: true,
3070
+ usage: { state: readMindState(now), rules: MIND_RULES },
3071
+ });
3072
+ }
3073
+
3074
+ function handleMindState(res) {
3075
+ const config = readPetChat();
3076
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
3077
+ res.end(JSON.stringify({
3078
+ ok: true,
3079
+ enabled: config.proactive.enabled === true,
3080
+ config: config.proactive,
3081
+ state: readMindState(),
3082
+ rules: MIND_RULES,
3083
+ silent: isSilent(),
3084
+ }));
3085
+ }
3086
+
3087
+ /* ── v1.2 屏幕感知:采样 + 观察记录 ─────────────────────────────────────── */
3088
+
3089
+ /** 采样节流状态(进程内;重启重置)。 */
3090
+ const observeLast = { foregroundAt: 0, ocrAt: 0, text: '', textAt: 0 };
3091
+ let observeTimer = null;
3092
+
3093
+ /**
3094
+ * 采一次:Level 1 前台窗口 → Level 2(可选)屏幕 OCR。
3095
+ * 默认关(`screen.mode === 'off'` 时**不调用任何 PowerShell**)。
3096
+ * @param {{force?:boolean}} [options]
3097
+ */
3098
+ async function observeOnce(options = {}) {
3099
+ const config = readPetChat();
3100
+ if (config.screen.mode === 'off') return { ok: false, reason: 'disabled', records: 0 };
3101
+ const persona = getActivePersona();
3102
+ if (!persona) return { ok: false, reason: 'no-persona', records: 0 };
3103
+ const now = nowMs();
3104
+ if (!options.force && observeLast.foregroundAt && now - observeLast.foregroundAt < OBSERVE_RULES.foregroundMs) {
3105
+ return { ok: false, reason: 'throttled', records: 0 };
3106
+ }
3107
+ observeLast.foregroundAt = now;
3108
+ const foreground = await readForegroundWindow();
3109
+ if (!foreground.ok) return { ok: false, reason: foreground.reason || 'foreground-failed', records: 0 };
3110
+ if (foreground.locked || isLockScreen(foreground.app, foreground.title)) {
3111
+ return { ok: false, reason: 'locked', records: 0 };
3112
+ }
3113
+ if (foreground.sensitive || isSensitiveApp(foreground.app, foreground.title)) {
3114
+ return { ok: false, reason: 'sensitive', records: 0, app: foreground.app };
3115
+ }
3116
+ let records = 0;
3117
+ const text = foregroundObservation(foreground);
3118
+ if (text && (options.force || text !== observeLast.text || now - observeLast.textAt > OBSERVE_RULES.dedupeMs)) {
3119
+ recordObservation(persona.id, { text, importance: 2, source: 'foreground' });
3120
+ observeLast.text = text;
3121
+ observeLast.textAt = now;
3122
+ records += 1;
3123
+ }
3124
+ let ocr = null;
3125
+ if (config.screen.mode === 'ocr' && (options.force || !observeLast.ocrAt || now - observeLast.ocrAt >= OBSERVE_RULES.ocrMs)) {
3126
+ observeLast.ocrAt = now;
3127
+ ocr = await captureScreenOcr({ maxChars: 600 });
3128
+ const ocrText = ocrObservation(ocr);
3129
+ if (ocrText) {
3130
+ recordObservation(persona.id, { text: ocrText, importance: 3, source: 'ocr' });
3131
+ records += 1;
3132
+ }
3133
+ }
3134
+ return {
3135
+ ok: true, records,
3136
+ app: foreground.app, title: foreground.title,
3137
+ ocr: ocr ? { ok: ocr.ok, chars: ocr.chars || 0, reason: ocr.reason || '' } : null,
3138
+ mode: config.screen.mode,
3139
+ };
3140
+ }
3141
+
3142
+ function observeStatus() {
3143
+ const config = readPetChat();
3144
+ const persona = getActivePersona();
3145
+ return {
3146
+ ok: true,
3147
+ mode: config.screen.mode,
3148
+ enabled: config.screen.mode !== 'off',
3149
+ confirmed: config.screen.confirmed === true,
3150
+ records: persona ? listObservations(persona.id, { limit: 1 }).total : 0,
3151
+ personaId: persona ? persona.id : '',
3152
+ rules: OBSERVE_RULES,
3153
+ };
3154
+ }
3155
+
3156
+ async function handleObserveSample(req, res) {
3157
+ let body = {};
3158
+ try { body = await readJsonBody(req); } catch { body = {}; }
3159
+ const result = await observeOnce({ force: body.force !== false });
3160
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
3161
+ res.end(JSON.stringify(result));
3162
+ }
3163
+
3164
+ /**
3165
+ * 后台采样循环:**每 30 秒问一次设置**,只有 `screen.mode !== 'off'` 才真的读窗口/截屏。
3166
+ * 定时器 `unref()`,不会拖住宿主退出;卸载时清掉。
3167
+ */
3168
+ function startObserveLoop() {
3169
+ if (observeTimer) return;
3170
+ observeTimer = setInterval(() => {
3171
+ void observeOnce().catch(() => {});
3172
+ }, 30000);
3173
+ if (typeof observeTimer.unref === 'function') observeTimer.unref();
3174
+ }
3175
+
2829
3176
  /** 手动静默(设置页的「暂时不说话」用;语音指令走 handleChat 里的解析)。 */
2830
3177
  async function handleSilence(req, res) {
2831
3178
  let body = {};
@@ -3858,6 +4205,9 @@ async function handleMicTest(req, res) {
3858
4205
  }
3859
4206
  }
3860
4207
  const rawVoice = readVoiceRaw();
4208
+ // v1.2:Edge 429 时前端只给一条提示 + 本地音色,不把 8 个灰项堆进列表。
4209
+ const rateLimited = (Array.isArray(voices) ? voices : []).some((voice) => voice && voice.engine === 'edge'
4210
+ && voice.usable !== true && /429|rate.?limit/i.test(String(voice.reason || '')));
3861
4211
  jsonSend(res, {
3862
4212
  ok: true,
3863
4213
  voices: Array.isArray(voices) ? voices : [],
@@ -3866,6 +4216,7 @@ async function handleMicTest(req, res) {
3866
4216
  continuous: rawVoice.continuous !== false,
3867
4217
  meta,
3868
4218
  providers: onlineProviderView(),
4219
+ rateLimited,
3869
4220
  // 下拉只该出现 usable=true;这里保留 false 条目仅用于排障(旧判据也依赖它)。
3870
4221
  usable: (Array.isArray(voices) ? voices : []).filter((v) => v && v.usable === true),
3871
4222
  });
@@ -4092,6 +4443,74 @@ async function handleMicTest(req, res) {
4092
4443
  jsonSend(res, { ok: true, ...result, packs: listPacks(), center: publicVoiceCenter() });
4093
4444
  }
4094
4445
 
4446
+ /** GET /pet-chat/voice/user-packs —— 用户导入的角色音色包 + 4 个内置系统音效。 */
4447
+ function handleUserVoicePacks(res) {
4448
+ jsonSend(res, voicePackSummary());
4449
+ }
4450
+
4451
+ /**
4452
+ * POST /pet-chat/voice/user-packs/import —— 导入用户自己的 voice pack。
4453
+ * 必须带 license + author(授权硬门槛);参考音频只存到用户目录,不进 npm 包、不上传。
4454
+ */
4455
+ async function handleUserVoicePackImport(req, res) {
4456
+ let body = {};
4457
+ try { body = await readJsonBody(req, 12 * 1024 * 1024); } catch { body = null; }
4458
+ if (!body || typeof body !== 'object') {
4459
+ jsonSend(res, { ok: false, code: 'bad-json', hint: '请求体不是合法 JSON' }, 400);
4460
+ return;
4461
+ }
4462
+ const result = importVoicePack(body);
4463
+ if (!result.ok) {
4464
+ jsonSend(res, {
4465
+ ok: false, code: result.error, hint: result.hint,
4466
+ // 界面直接展示授权口径:不让用户以为“导入=可以随便用别人的声音”
4467
+ policy: '角色语音必须由你拥有权利:请填写 license 与作者/来源;本插件不提供、不分发角色/声优素材。',
4468
+ }, 400);
4469
+ return;
4470
+ }
4471
+ jsonSend(res, { ok: true, pack: result.pack, packs: voicePackSummary() }, 201);
4472
+ }
4473
+
4474
+ /** POST /pet-chat/voice/user-packs/remove { id } */
4475
+ async function handleUserVoicePackRemove(req, res) {
4476
+ let body = {};
4477
+ try { body = await readJsonBody(req); } catch { body = {}; }
4478
+ const result = removeUserVoicePack(body.id);
4479
+ if (!result.ok) {
4480
+ jsonSend(res, { ok: false, code: result.error, hint: '没有这个音色包或删除失败' }, 400);
4481
+ return;
4482
+ }
4483
+ jsonSend(res, { ok: true, ...result, packs: voicePackSummary() });
4484
+ }
4485
+
4486
+ /** GET /pet-chat/system-sounds —— 内置 4 个音效(授权:本仓库合成,MIT)。 */
4487
+ function handleSystemSounds(res) {
4488
+ jsonSend(res, {
4489
+ ok: true,
4490
+ sounds: listSystemSounds(),
4491
+ count: SYSTEM_SOUNDS.length,
4492
+ policy: '内置只有 4 个系统音效;角色语音走下载/导入,不进 npm 包。',
4493
+ });
4494
+ }
4495
+
4496
+ /** GET /pet-chat/system-sounds/<id>.wav —— 直出内置音效(只认白名单)。 */
4497
+ function handleSystemSoundAudio(req, res, name) {
4498
+ const clean = String(name || '').replace(/\.wav$/i, '');
4499
+ const sound = SYSTEM_SOUNDS.find((item) => item.id === clean);
4500
+ if (!sound) { jsonSend(res, { ok: false, code: 'not-found' }, 404); return; }
4501
+ let bytes;
4502
+ try {
4503
+ bytes = readFileSync(new URL('../../assets/system/sound/' + sound.file, import.meta.url));
4504
+ } catch {
4505
+ jsonSend(res, { ok: false, code: 'missing-asset', hint: '这个音效文件没随包发布' }, 404);
4506
+ return;
4507
+ }
4508
+ res.statusCode = 200;
4509
+ res.setHeader('Content-Type', 'audio/wav');
4510
+ res.setHeader('Cache-Control', 'public, max-age=86400');
4511
+ res.end(bytes);
4512
+ }
4513
+
4095
4514
  /** POST /pet-chat/voice/packs/default { id } —— 设为全局默认音色。 */
4096
4515
  async function handleVoicePackDefault(req, res) {
4097
4516
  let body = {};
@@ -4478,9 +4897,9 @@ async function handleMicTest(req, res) {
4478
4897
  };
4479
4898
  }
4480
4899
  const lyricLines = Array.isArray(args.lyrics)
4481
- ? args.lyrics
4900
+ ? args.lyrics.map((line) => sanitizeLyrics(line)).filter(Boolean)
4482
4901
  : (typeof args.lyrics === 'string' && args.lyrics.trim()
4483
- ? String(args.lyrics).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
4902
+ ? String(args.lyrics).split(/\r?\n/).map((line) => sanitizeLyrics(line)).filter(Boolean)
4484
4903
  : []);
4485
4904
  const plan = planSing({
4486
4905
  topic: String(args.topic || '今天').slice(0, 20),
@@ -4797,6 +5216,13 @@ async function handleMicTest(req, res) {
4797
5216
  if (tail === '/voice/packs/install' && method === 'POST') { await handleVoicePackInstall(req, res); return; }
4798
5217
  if (tail === '/voice/packs/remove' && method === 'POST') { await handleVoicePackRemove(req, res); return; }
4799
5218
  if (tail === '/voice/packs/default' && method === 'POST') { await handleVoicePackDefault(req, res); return; }
5219
+ // v1.2 用户音色包(角色语音走导入,不进 npm 包)+ 4 个内置系统音效
5220
+ if (tail === '/voice/user-packs' && (method === 'GET' || method === 'HEAD')) { handleUserVoicePacks(res); return; }
5221
+ if (tail === '/voice/user-packs/import' && method === 'POST') { await handleUserVoicePackImport(req, res); return; }
5222
+ if (tail === '/voice/user-packs/remove' && method === 'POST') { await handleUserVoicePackRemove(req, res); return; }
5223
+ if (tail === '/system-sounds' && (method === 'GET' || method === 'HEAD')) { handleSystemSounds(res); return; }
5224
+ const systemSoundMatch = /^\/system-sounds\/([^/]+\.wav)$/.exec(tail);
5225
+ if (systemSoundMatch && (method === 'GET' || method === 'HEAD')) { handleSystemSoundAudio(req, res, systemSoundMatch[1]); return; }
4800
5226
  if (tail === '/voice/preferred' && (method === 'GET' || method === 'HEAD' || method === 'POST')) { await handleVoicePreferred(req, res); return; }
4801
5227
  if (tail === '/voice/preview' && method === 'POST') { await handleVoicePreview(req, res); return; }
4802
5228
  if (tail === '/tts/preview' && method === 'POST') { await handleVoicePreview(req, res); return; }
@@ -4848,6 +5274,30 @@ if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatu
4848
5274
  return;
4849
5275
  }
4850
5276
  if (tail === '/proactive/tick' && method === 'POST') { await handleProactiveTick(req, res); return; }
5277
+ // v1.2 主动思维:没有外部事件时的“内心 tick”(默认关;勿扰/静默/忙碌时只说 record 或 none)
5278
+ if (tail === '/mind/tick' && method === 'POST') { await handleMindTick(req, res); return; }
5279
+ if (tail === '/mind/state' && (method === 'GET' || method === 'HEAD')) { handleMindState(res); return; }
5280
+ if (tail === '/mind/reset' && method === 'POST') {
5281
+ clearMindState();
5282
+ jsonSend(res, { ok: true });
5283
+ return;
5284
+ }
5285
+ // v1.2 屏幕感知 / 被动观察:默认关;关闭时连 PowerShell 都不启动
5286
+ if (tail === '/observe/status' && (method === 'GET' || method === 'HEAD')) { jsonSend(res, observeStatus()); return; }
5287
+ if (tail === '/observe/sample' && method === 'POST') { await handleObserveSample(req, res); return; }
5288
+ if (tail === '/observe/records' && (method === 'GET' || method === 'HEAD')) {
5289
+ const persona = getActivePersona();
5290
+ if (!persona) { jsonSend(res, { ok: false, code: 'no-persona', items: [] }); return; }
5291
+ const offset = Number(url.searchParams.get('offset') || 0);
5292
+ const limit = Number(url.searchParams.get('limit') || 50);
5293
+ jsonSend(res, { ok: true, personaId: persona.id, ...listObservations(persona.id, { offset, limit }) });
5294
+ return;
5295
+ }
5296
+ if (tail === '/observe/records' && method === 'DELETE') {
5297
+ const persona = getActivePersona();
5298
+ jsonSend(res, { ok: true, personaId: persona && persona.id, ...(persona ? clearObservations(persona.id) : { removed: 0 }) });
5299
+ return;
5300
+ }
4851
5301
  if (tail === '/silence' && method === 'POST') { await handleSilence(req, res); return; }
4852
5302
  if (tail === '/memory' && (method === 'GET' || method === 'HEAD')) {
4853
5303
  // 旧入口保留给气泡「查看记忆」;数据源已切到 active persona 的事件流,不再读旧 memory.json。
@@ -4878,8 +5328,12 @@ if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatu
4878
5328
  },
4879
5329
  }));
4880
5330
 
5331
+ // v1.2:屏幕感知采样(每 30 秒看一次设置;off 时不调用任何外部进程)
5332
+ startObserveLoop();
5333
+
4881
5334
  // 卸载:断开所有事件流 + 停掉懒启动的 TTS worker(不留后台进程)
4882
5335
  disposers.push(() => {
5336
+ if (observeTimer) { try { clearInterval(observeTimer); } catch { /* ignore */ } observeTimer = null; }
4883
5337
  pendingConfirms.clear();
4884
5338
  pendingConfirmById.clear();
4885
5339
  for (const hit of pendingClientActions.values()) {