dsh-folia 1.1.0 → 1.2.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,
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,
@@ -805,13 +827,24 @@ export function registerPetChatRoutes(webServer, c) {
805
827
  * pre.65:system 由 core/growth/express/affect/世界书/召回记忆组成,不再读旧 memory.json。
806
828
  */
807
829
  function buildRequest(config, text, context = {}, persona = null) {
808
- const system = persona
830
+ // v1.2:关系/好感度 + 世界书 RAG(lore)都只作背景注入,不整本塞 prompt。
831
+ let memoryExtras = '';
832
+ if (persona) {
833
+ try {
834
+ const relations = relationsPromptLine(persona.id);
835
+ if (relations) memoryExtras += '\n' + relations;
836
+ } catch { /* ignore */ }
837
+ try { const lore = lorePromptLine(persona.id, text); if (lore) memoryExtras += '\n' + lore; } catch { /* ignore */ }
838
+ }
839
+ const baseSystem = persona
809
840
  ? buildPersonaSystemPrompt(persona, {
810
841
  env: context.env || '',
811
842
  mood: context.mood || null,
812
843
  memories: context.memories || [],
813
844
  userText: text,
814
845
  inputMode: context.inputMode,
846
+ conversationMode: context.conversationMode,
847
+ voiceLength: context.voiceLength,
815
848
  // 任务 §3:内心步骤 / 先想过的要点 / 别重复的安慰话(都只进 system,不进历史)
816
849
  innerStep: context.innerStep || '',
817
850
  outline: context.outline || '',
@@ -819,9 +852,11 @@ export function registerPetChatRoutes(webServer, c) {
819
852
  affect: persona.affect,
820
853
  }) + '\n' + buildCapabilityPrompt()
821
854
  : buildSystemPrompt(config, {}, context.env || '', context.mood || null) + '\n' + buildCapabilityPrompt();
855
+ const system = baseSystem + memoryExtras;
822
856
  const headers = { 'content-type': 'application/json' };
823
857
  const history = persona ? historyFor(persona.id).slice(-config.maxTurns) : [];
824
858
  const temperature = Number(config.temperature);
859
+ const maxTokens = Math.max(0, Math.min(8192, Number(context.maxTokens) || 0));
825
860
  if (config.provider === 'openai') {
826
861
  if (config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
827
862
  return {
@@ -831,6 +866,7 @@ export function registerPetChatRoutes(webServer, c) {
831
866
  stream: true,
832
867
  temperature: Number.isFinite(temperature) ? temperature : 0.8,
833
868
  messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
869
+ ...(maxTokens ? { max_tokens: maxTokens } : {}),
834
870
  },
835
871
  headers,
836
872
  };
@@ -842,6 +878,7 @@ export function registerPetChatRoutes(webServer, c) {
842
878
  stream: true,
843
879
  temperature: Number.isFinite(temperature) ? temperature : 0.8,
844
880
  messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
881
+ ...(maxTokens ? { options: { num_predict: maxTokens } } : {}),
845
882
  },
846
883
  headers,
847
884
  };
@@ -899,6 +936,12 @@ export function registerPetChatRoutes(webServer, c) {
899
936
  voice,
900
937
  resolvedVoice,
901
938
  memoryEnabled: true,
939
+ // v1.2:客户端据此决定「讲故事/树洞/观察」的显示与朗读行为。
940
+ conversationMode: config.conversationMode,
941
+ voiceLength: config.voiceLength,
942
+ proactive: config.proactive,
943
+ screen: config.screen,
944
+ observing: config.screen.mode !== 'off',
902
945
  asrProvider: ASR_PROVIDER_ID,
903
946
  personas: persona ? {
904
947
  id: persona.id, name: persona.name, type: persona.type, mode: persona.mode,
@@ -1717,6 +1760,40 @@ export function registerPetChatRoutes(webServer, c) {
1717
1760
 
1718
1761
  const mood = detectMood(text, now);
1719
1762
  const inputMode = body.inputMode === 'voice' ? 'voice' : 'text';
1763
+ /** v1.2:本轮会话模式(请求可临时覆盖;最终回落设置里的默认模式)。 */
1764
+ const conversationMode = ['chat', 'story', 'treehole', 'observe'].includes(String(body.conversationMode || ''))
1765
+ ? String(body.conversationMode) : config.conversationMode;
1766
+
1767
+ /**
1768
+ * 只观察模式:**不回答、不弹气泡**(宿主侧兜底;客户端也会在 mode=observe 时挡掉请求)。
1769
+ * 真正的“观察记录”由 /observe 采样器写入,与对话无关。
1770
+ */
1771
+ if (conversationMode === 'observe') {
1772
+ sse(res, 'meta', { mood: mood.mood, rate: mood.rate, mode: 'observe' });
1773
+ sse(res, 'done', { emotion: 'calm', skipped: 'observe', conversationMode, personaId: persona.id });
1774
+ res.end();
1775
+ return;
1776
+ }
1777
+
1778
+ /* ── 树洞安全:命中自伤/危机词先用固定回应接住,不交给模型自由发挥 ── */
1779
+ if (conversationMode === 'treehole') {
1780
+ const hit = detectCrisis(text);
1781
+ if (hit) {
1782
+ const safety = treeholeSafetyReply((config.treehole && config.treehole.hotline) || '12356');
1783
+ recordPersonaEvent(persona, {
1784
+ kind: 'treehole', importance: 8,
1785
+ text: `树洞·危机词(${hit}):用户需要安全支持`,
1786
+ });
1787
+ sse(res, 'meta', { mood: mood.mood, rate: mood.rate, mode: 'treehole', safety: true });
1788
+ sse(res, 'delta', { t: safety });
1789
+ sse(res, 'done', {
1790
+ emotion: 'calm', safety: true, crisis: hit, conversationMode, personaId: persona.id,
1791
+ mood: mood.mood, rate: mood.rate,
1792
+ });
1793
+ res.end();
1794
+ return;
1795
+ }
1796
+ }
1720
1797
 
1721
1798
  /**
1722
1799
  * 权限确认:**只有下一句是确认才执行**。
@@ -1983,6 +2060,8 @@ export function registerPetChatRoutes(webServer, c) {
1983
2060
  : [];
1984
2061
  const request = buildRequest(config, text, {
1985
2062
  env, mood, memories: recalled.items, inputMode, innerStep: inner.text, outline, avoidLines,
2063
+ conversationMode, voiceLength: config.voiceLength,
2064
+ maxTokens: conversationMode === 'story' ? 6000 : 0,
1986
2065
  }, persona);
1987
2066
  // v5 §5:三档思考(语音/寒暄 quick;文字复杂 standard;分析/规划/写作 deep)。
1988
2067
  const tier = thinkingTier(text, { inputMode });
@@ -2003,6 +2082,8 @@ export function registerPetChatRoutes(webServer, c) {
2003
2082
  emotion, usage: usage || null, intent: intent.intent, tier,
2004
2083
  mood: mood.mood, rate: mood.rate, personaId: persona.id, personaType: persona.type,
2005
2084
  memories: recalled.items.length, memoryTokens: recalled.tokens,
2085
+ conversationMode, voiceLength: config.voiceLength,
2086
+ ...(conversationMode === 'story' ? { story: true } : {}),
2006
2087
  });
2007
2088
  res.end();
2008
2089
  };
@@ -2076,7 +2157,16 @@ export function registerPetChatRoutes(webServer, c) {
2076
2157
  let buffer = '';
2077
2158
  let full = '';
2078
2159
  // 兼容老判据:不带 inputMode 的请求仍按旧 maxChars 截断;前端/新判据显式带 text/voice。
2079
- const legacyLimit = body.inputMode ? 0 : (Number(config.legacyMaxChars) || 80);
2160
+ const legacyLimit = body.inputMode || conversationMode === 'story' ? 0 : (Number(config.legacyMaxChars) || 80);
2161
+ /**
2162
+ * v1.2 语音回答长度:**只在 chat 模式**按句数限制(3/8/不限,默认 8)。
2163
+ * story / treehole 不限制(讲故事必须完整到结尾;树洞允许短句但不受句数卡)。
2164
+ * 到上限后**不 cancel 流**:模型继续生成、历史保留完整,只是不再往气泡推 delta ——
2165
+ * 这样“截断只发生在显示/朗读层”,宿主不提前结束这一轮。
2166
+ */
2167
+ const voiceLimit = conversationMode === 'chat' && inputMode === 'voice'
2168
+ ? Math.max(0, Number(config.voiceLength) || 0) : 0;
2169
+ let voiceLimitReached = false;
2080
2170
  let stopped = false;
2081
2171
  const appendPiece = (piece) => {
2082
2172
  let chunk = String(piece || '');
@@ -2086,23 +2176,31 @@ export function registerPetChatRoutes(webServer, c) {
2086
2176
  if (room <= 0) return false;
2087
2177
  if (chunk.length > room) chunk = chunk.slice(0, room);
2088
2178
  }
2089
- if (inputMode === 'voice') {
2090
- // 语音模式:最多 3 句;到第 3 个句末就停(不再把第 4 句推给 TTS)。
2179
+ if (voiceLimit > 0) {
2180
+ const combined = full + chunk;
2181
+ if (voiceLimitReached) {
2182
+ full = combined;
2183
+ return true;
2184
+ }
2091
2185
  let sentences = 0;
2092
2186
  let cut = -1;
2093
- const combined = full + chunk;
2094
2187
  for (let i = 0; i < combined.length; i += 1) {
2095
2188
  if (/[。!?!?]/.test(combined[i])) {
2096
2189
  sentences += 1;
2097
- if (sentences >= 3) { cut = i + 1; break; }
2190
+ if (sentences >= voiceLimit) { cut = i + 1; break; }
2098
2191
  }
2099
2192
  }
2100
- if (cut >= 0) {
2101
- chunk = combined.slice(0, cut);
2102
- full = chunk;
2103
- sse(res, 'delta', { t: chunk });
2104
- return false;
2193
+ if (cut >= 0 && cut < combined.length) {
2194
+ const visible = combined.slice(full.length, cut);
2195
+ full = combined;
2196
+ voiceLimitReached = true;
2197
+ if (visible) sse(res, 'delta', { t: visible });
2198
+ return true;
2105
2199
  }
2200
+ full = combined;
2201
+ sse(res, 'delta', { t: chunk });
2202
+ if (cut === combined.length) voiceLimitReached = true;
2203
+ return true;
2106
2204
  }
2107
2205
  full += chunk;
2108
2206
  sse(res, 'delta', { t: chunk });
@@ -2133,6 +2231,15 @@ export function registerPetChatRoutes(webServer, c) {
2133
2231
  pushRecentReply(persona.id, parsed.reply);
2134
2232
  recordPersonaEvent(persona, { kind: 'chat', importance: 4, text: `用户:${text.slice(0, 500)}` });
2135
2233
  recordPersonaEvent(persona, { kind: 'chat', importance: 5, text: `我:${parsed.reply.slice(0, 1000)}` });
2234
+ // v1.2:树洞要记住“在意的事/情绪触发点”(importance 6–8),而不是普通闲聊。
2235
+ if (conversationMode === 'treehole') {
2236
+ recordPersonaEvent(persona, {
2237
+ kind: 'treehole', importance: 7,
2238
+ text: `树洞:用户说「${text.slice(0, 200)}」(先接情绪,不急着建议)`,
2239
+ });
2240
+ }
2241
+ // v1.2:从对话里抽实体写关系/好感度(保守规则,见 memory-db.extractEntities)。
2242
+ try { touchRelations(persona.id, text); } catch { /* 关系抽取失败不影响回复 */ }
2136
2243
  maybeReflect(persona, config);
2137
2244
  done(emotion, { chars: parsed.reply.length });
2138
2245
  } catch (error) {
@@ -2657,6 +2764,12 @@ const roots = [
2657
2764
  ownerName: config.ownerName,
2658
2765
  voice: publicVoice(readVoiceRaw()),
2659
2766
  wake: config.wake,
2767
+ // v1.2
2768
+ conversationMode: config.conversationMode,
2769
+ voiceLength: config.voiceLength,
2770
+ proactive: config.proactive,
2771
+ screen: config.screen,
2772
+ treehole: config.treehole,
2660
2773
  },
2661
2774
  }));
2662
2775
  }
@@ -2709,6 +2822,42 @@ const roots = [
2709
2822
  };
2710
2823
  }
2711
2824
 
2825
+ /* ── v1.2 会话模式 / 语音长度 / 主动思维 / 屏幕感知 / 树洞 ───────────── */
2826
+ const modeList = ['chat', 'story', 'treehole', 'observe'];
2827
+ if (typeof body.conversationMode === 'string' && modeList.includes(body.conversationMode)) {
2828
+ patch.conversationMode = body.conversationMode;
2829
+ }
2830
+ if ([0, 3, 8].includes(Number(body.voiceLength))) patch.voiceLength = Number(body.voiceLength);
2831
+ if (body.proactive && typeof body.proactive === 'object') {
2832
+ const previous = current.proactive || {};
2833
+ const interval = [0, 15, 30, 60].includes(Number(body.proactive.intervalMin))
2834
+ ? Number(body.proactive.intervalMin) : previous.intervalMin;
2835
+ const clock = (value, fallback) => (/^([01]\d|2[0-3]):[0-5]\d$/.test(String(value || '')) ? String(value) : fallback);
2836
+ patch.proactive = {
2837
+ enabled: body.proactive.enabled === true && interval !== 0,
2838
+ intervalMin: interval,
2839
+ quietFrom: clock(body.proactive.quietFrom, previous.quietFrom),
2840
+ quietTo: clock(body.proactive.quietTo, previous.quietTo),
2841
+ };
2842
+ }
2843
+ if (body.screen && typeof body.screen === 'object') {
2844
+ const previous = current.screen || { mode: 'off', confirmed: false };
2845
+ const mode = ['off', 'app', 'ocr'].includes(body.screen.mode) ? body.screen.mode : previous.mode;
2846
+ // 从 off 打开任何一级都要**二次确认**(UI 弹说明后带 confirm:true 再来一次);
2847
+ // 单纯把 confirmed 置 true 但不改 mode 不允许,避免“绕过说明直接开”。
2848
+ if (mode !== 'off' && previous.mode === 'off' && body.screen.confirm !== true) {
2849
+ send({ ok: false, code: 'screen-confirm-required', hint: '开启屏幕感知前需要先看说明并二次确认' }, 409);
2850
+ return;
2851
+ }
2852
+ patch.screen = { mode, confirmed: mode === 'off' ? false : (body.screen.confirm === true || previous.confirmed === true) };
2853
+ }
2854
+ if (body.treehole && typeof body.treehole === 'object') {
2855
+ patch.treehole = {
2856
+ hotline: typeof body.treehole.hotline === 'string' && body.treehole.hotline.trim()
2857
+ ? body.treehole.hotline.trim().slice(0, 40) : (current.treehole || {}).hotline || '12356',
2858
+ };
2859
+ }
2860
+
2712
2861
  writeOverlay(patch);
2713
2862
  const config = readPetChat();
2714
2863
  send({
@@ -2803,6 +2952,7 @@ const roots = [
2803
2952
  }));
2804
2953
  return;
2805
2954
  }
2955
+ const config = readPetChat();
2806
2956
  const decision = canSpeak({
2807
2957
  idleMinutes: Number(body.idleMinutes) || 0,
2808
2958
  fullscreen: body.fullscreen === true,
@@ -2810,6 +2960,13 @@ const roots = [
2810
2960
  now,
2811
2961
  });
2812
2962
  let line = null;
2963
+ // v1.2:主动搭话默认关。静默(用户说过“别说了”)优先于“默认关”,
2964
+ // 这样排障时能明确区分 “silent” 与 “disabled”。
2965
+ if (!decision.ok && decision.reason !== 'silent' && config.proactive.enabled !== true) {
2966
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
2967
+ res.end(JSON.stringify({ ok: false, reason: 'disabled', line: null, usage: todayUsage(now), enabled: false }));
2968
+ return;
2969
+ }
2813
2970
  if (decision.ok) {
2814
2971
  const state = readProactiveState(now);
2815
2972
  const active = getActivePersona();
@@ -2826,6 +2983,180 @@ const roots = [
2826
2983
  res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage(now) }));
2827
2984
  }
2828
2985
 
2986
+ /* ── v1.2 主动思维(内心 tick)────────────────────────────────────────── */
2987
+
2988
+ /**
2989
+ * 一次内心 tick:先过设置/勿扰/忙碌/静默闸门,再让 pet-chat-mind 决策。
2990
+ * 与 `/proactive/tick` 的区别:这是**没有外部事件**时的主动思考(默认关)。
2991
+ */
2992
+ async function handleMindTick(req, res) {
2993
+ let body = {};
2994
+ try { body = await readJsonBody(req); } catch { body = {}; }
2995
+ const send = (payload, status = 200) => {
2996
+ res.statusCode = status;
2997
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
2998
+ res.end(JSON.stringify(payload));
2999
+ };
3000
+ const config = readPetChat();
3001
+ const now = nowMs();
3002
+ const persona = getActivePersona();
3003
+ // 静默口令优先于“默认关”:用户说过“别说了”,任何 tick 都回 silent。
3004
+ if (isSilent(now)) {
3005
+ send({ ok: false, reason: 'silent', action: 'none', line: '', enabled: config.proactive.enabled });
3006
+ return;
3007
+ }
3008
+ if (config.proactive.enabled !== true) {
3009
+ send({ ok: false, reason: 'disabled', action: 'none', line: '', enabled: false });
3010
+ return;
3011
+ }
3012
+ let foreground = null;
3013
+ if (config.screen.mode !== 'off') {
3014
+ try { foreground = await readForegroundWindow(); } catch { foreground = null; }
3015
+ if (foreground && (foreground.locked || foreground.sensitive)) foreground = null;
3016
+ }
3017
+ const memories = persona ? retrieveEvents(persona.id, '', { topK: 3, tokenBudget: 300 }).items : [];
3018
+ const decision = mindTick({
3019
+ now,
3020
+ enabled: true,
3021
+ intervalMin: config.proactive.intervalMin,
3022
+ quietFrom: config.proactive.quietFrom,
3023
+ quietTo: config.proactive.quietTo,
3024
+ speaking: body.speaking === true,
3025
+ listening: body.listening === true,
3026
+ turnBusy: body.turnBusy === true,
3027
+ muted: Boolean(config.voice && config.voice.muted),
3028
+ silent: isSilent(now),
3029
+ activeMinutes: Number(body.activeMinutes) || 0,
3030
+ app: foreground ? foreground.app : '',
3031
+ title: foreground ? foreground.title : '',
3032
+ wallpaperTitle: body.wallpaperTitle,
3033
+ memories,
3034
+ observationText: body.observationText,
3035
+ state: readMindState(now),
3036
+ });
3037
+ if ((decision.action === 'speak' || decision.action === 'ask') && decision.line) {
3038
+ markMindSaid(now, decision.line, decision.kind);
3039
+ if (persona) {
3040
+ recordPersonaEvent(persona, { kind: 'event', importance: 3, text: `我主动搭话:${decision.line.slice(0, 200)}` });
3041
+ }
3042
+ // 只有真的“过闸并落地”才记账:被勿扰/静默挡下的 tick 不该吃掉 15 分钟间隔。
3043
+ markMindTick(now);
3044
+ } else if (decision.action === 'record') {
3045
+ if (body.observationText && persona) {
3046
+ recordObservation(persona.id, { text: String(body.observationText).slice(0, 200), importance: 2, source: 'mind' });
3047
+ }
3048
+ markMindTick(now);
3049
+ }
3050
+ send({
3051
+ ok: decision.action === 'speak' || decision.action === 'ask',
3052
+ ...decision,
3053
+ enabled: true,
3054
+ usage: { state: readMindState(now), rules: MIND_RULES },
3055
+ });
3056
+ }
3057
+
3058
+ function handleMindState(res) {
3059
+ const config = readPetChat();
3060
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
3061
+ res.end(JSON.stringify({
3062
+ ok: true,
3063
+ enabled: config.proactive.enabled === true,
3064
+ config: config.proactive,
3065
+ state: readMindState(),
3066
+ rules: MIND_RULES,
3067
+ silent: isSilent(),
3068
+ }));
3069
+ }
3070
+
3071
+ /* ── v1.2 屏幕感知:采样 + 观察记录 ─────────────────────────────────────── */
3072
+
3073
+ /** 采样节流状态(进程内;重启重置)。 */
3074
+ const observeLast = { foregroundAt: 0, ocrAt: 0, text: '', textAt: 0 };
3075
+ let observeTimer = null;
3076
+
3077
+ /**
3078
+ * 采一次:Level 1 前台窗口 → Level 2(可选)屏幕 OCR。
3079
+ * 默认关(`screen.mode === 'off'` 时**不调用任何 PowerShell**)。
3080
+ * @param {{force?:boolean}} [options]
3081
+ */
3082
+ async function observeOnce(options = {}) {
3083
+ const config = readPetChat();
3084
+ if (config.screen.mode === 'off') return { ok: false, reason: 'disabled', records: 0 };
3085
+ const persona = getActivePersona();
3086
+ if (!persona) return { ok: false, reason: 'no-persona', records: 0 };
3087
+ const now = nowMs();
3088
+ if (!options.force && observeLast.foregroundAt && now - observeLast.foregroundAt < OBSERVE_RULES.foregroundMs) {
3089
+ return { ok: false, reason: 'throttled', records: 0 };
3090
+ }
3091
+ observeLast.foregroundAt = now;
3092
+ const foreground = await readForegroundWindow();
3093
+ if (!foreground.ok) return { ok: false, reason: foreground.reason || 'foreground-failed', records: 0 };
3094
+ if (foreground.locked || isLockScreen(foreground.app, foreground.title)) {
3095
+ return { ok: false, reason: 'locked', records: 0 };
3096
+ }
3097
+ if (foreground.sensitive || isSensitiveApp(foreground.app, foreground.title)) {
3098
+ return { ok: false, reason: 'sensitive', records: 0, app: foreground.app };
3099
+ }
3100
+ let records = 0;
3101
+ const text = foregroundObservation(foreground);
3102
+ if (text && (options.force || text !== observeLast.text || now - observeLast.textAt > OBSERVE_RULES.dedupeMs)) {
3103
+ recordObservation(persona.id, { text, importance: 2, source: 'foreground' });
3104
+ observeLast.text = text;
3105
+ observeLast.textAt = now;
3106
+ records += 1;
3107
+ }
3108
+ let ocr = null;
3109
+ if (config.screen.mode === 'ocr' && (options.force || !observeLast.ocrAt || now - observeLast.ocrAt >= OBSERVE_RULES.ocrMs)) {
3110
+ observeLast.ocrAt = now;
3111
+ ocr = await captureScreenOcr({ maxChars: 600 });
3112
+ const ocrText = ocrObservation(ocr);
3113
+ if (ocrText) {
3114
+ recordObservation(persona.id, { text: ocrText, importance: 3, source: 'ocr' });
3115
+ records += 1;
3116
+ }
3117
+ }
3118
+ return {
3119
+ ok: true, records,
3120
+ app: foreground.app, title: foreground.title,
3121
+ ocr: ocr ? { ok: ocr.ok, chars: ocr.chars || 0, reason: ocr.reason || '' } : null,
3122
+ mode: config.screen.mode,
3123
+ };
3124
+ }
3125
+
3126
+ function observeStatus() {
3127
+ const config = readPetChat();
3128
+ const persona = getActivePersona();
3129
+ return {
3130
+ ok: true,
3131
+ mode: config.screen.mode,
3132
+ enabled: config.screen.mode !== 'off',
3133
+ confirmed: config.screen.confirmed === true,
3134
+ records: persona ? listObservations(persona.id, { limit: 1 }).total : 0,
3135
+ personaId: persona ? persona.id : '',
3136
+ rules: OBSERVE_RULES,
3137
+ };
3138
+ }
3139
+
3140
+ async function handleObserveSample(req, res) {
3141
+ let body = {};
3142
+ try { body = await readJsonBody(req); } catch { body = {}; }
3143
+ const result = await observeOnce({ force: body.force !== false });
3144
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
3145
+ res.end(JSON.stringify(result));
3146
+ }
3147
+
3148
+ /**
3149
+ * 后台采样循环:**每 30 秒问一次设置**,只有 `screen.mode !== 'off'` 才真的读窗口/截屏。
3150
+ * 定时器 `unref()`,不会拖住宿主退出;卸载时清掉。
3151
+ */
3152
+ function startObserveLoop() {
3153
+ if (observeTimer) return;
3154
+ observeTimer = setInterval(() => {
3155
+ void observeOnce().catch(() => {});
3156
+ }, 30000);
3157
+ if (typeof observeTimer.unref === 'function') observeTimer.unref();
3158
+ }
3159
+
2829
3160
  /** 手动静默(设置页的「暂时不说话」用;语音指令走 handleChat 里的解析)。 */
2830
3161
  async function handleSilence(req, res) {
2831
3162
  let body = {};
@@ -3858,6 +4189,9 @@ async function handleMicTest(req, res) {
3858
4189
  }
3859
4190
  }
3860
4191
  const rawVoice = readVoiceRaw();
4192
+ // v1.2:Edge 429 时前端只给一条提示 + 本地音色,不把 8 个灰项堆进列表。
4193
+ const rateLimited = (Array.isArray(voices) ? voices : []).some((voice) => voice && voice.engine === 'edge'
4194
+ && voice.usable !== true && /429|rate.?limit/i.test(String(voice.reason || '')));
3861
4195
  jsonSend(res, {
3862
4196
  ok: true,
3863
4197
  voices: Array.isArray(voices) ? voices : [],
@@ -3866,6 +4200,7 @@ async function handleMicTest(req, res) {
3866
4200
  continuous: rawVoice.continuous !== false,
3867
4201
  meta,
3868
4202
  providers: onlineProviderView(),
4203
+ rateLimited,
3869
4204
  // 下拉只该出现 usable=true;这里保留 false 条目仅用于排障(旧判据也依赖它)。
3870
4205
  usable: (Array.isArray(voices) ? voices : []).filter((v) => v && v.usable === true),
3871
4206
  });
@@ -4092,6 +4427,74 @@ async function handleMicTest(req, res) {
4092
4427
  jsonSend(res, { ok: true, ...result, packs: listPacks(), center: publicVoiceCenter() });
4093
4428
  }
4094
4429
 
4430
+ /** GET /pet-chat/voice/user-packs —— 用户导入的角色音色包 + 4 个内置系统音效。 */
4431
+ function handleUserVoicePacks(res) {
4432
+ jsonSend(res, voicePackSummary());
4433
+ }
4434
+
4435
+ /**
4436
+ * POST /pet-chat/voice/user-packs/import —— 导入用户自己的 voice pack。
4437
+ * 必须带 license + author(授权硬门槛);参考音频只存到用户目录,不进 npm 包、不上传。
4438
+ */
4439
+ async function handleUserVoicePackImport(req, res) {
4440
+ let body = {};
4441
+ try { body = await readJsonBody(req, 12 * 1024 * 1024); } catch { body = null; }
4442
+ if (!body || typeof body !== 'object') {
4443
+ jsonSend(res, { ok: false, code: 'bad-json', hint: '请求体不是合法 JSON' }, 400);
4444
+ return;
4445
+ }
4446
+ const result = importVoicePack(body);
4447
+ if (!result.ok) {
4448
+ jsonSend(res, {
4449
+ ok: false, code: result.error, hint: result.hint,
4450
+ // 界面直接展示授权口径:不让用户以为“导入=可以随便用别人的声音”
4451
+ policy: '角色语音必须由你拥有权利:请填写 license 与作者/来源;本插件不提供、不分发角色/声优素材。',
4452
+ }, 400);
4453
+ return;
4454
+ }
4455
+ jsonSend(res, { ok: true, pack: result.pack, packs: voicePackSummary() }, 201);
4456
+ }
4457
+
4458
+ /** POST /pet-chat/voice/user-packs/remove { id } */
4459
+ async function handleUserVoicePackRemove(req, res) {
4460
+ let body = {};
4461
+ try { body = await readJsonBody(req); } catch { body = {}; }
4462
+ const result = removeUserVoicePack(body.id);
4463
+ if (!result.ok) {
4464
+ jsonSend(res, { ok: false, code: result.error, hint: '没有这个音色包或删除失败' }, 400);
4465
+ return;
4466
+ }
4467
+ jsonSend(res, { ok: true, ...result, packs: voicePackSummary() });
4468
+ }
4469
+
4470
+ /** GET /pet-chat/system-sounds —— 内置 4 个音效(授权:本仓库合成,MIT)。 */
4471
+ function handleSystemSounds(res) {
4472
+ jsonSend(res, {
4473
+ ok: true,
4474
+ sounds: listSystemSounds(),
4475
+ count: SYSTEM_SOUNDS.length,
4476
+ policy: '内置只有 4 个系统音效;角色语音走下载/导入,不进 npm 包。',
4477
+ });
4478
+ }
4479
+
4480
+ /** GET /pet-chat/system-sounds/<id>.wav —— 直出内置音效(只认白名单)。 */
4481
+ function handleSystemSoundAudio(req, res, name) {
4482
+ const clean = String(name || '').replace(/\.wav$/i, '');
4483
+ const sound = SYSTEM_SOUNDS.find((item) => item.id === clean);
4484
+ if (!sound) { jsonSend(res, { ok: false, code: 'not-found' }, 404); return; }
4485
+ let bytes;
4486
+ try {
4487
+ bytes = readFileSync(new URL('../../assets/system/sound/' + sound.file, import.meta.url));
4488
+ } catch {
4489
+ jsonSend(res, { ok: false, code: 'missing-asset', hint: '这个音效文件没随包发布' }, 404);
4490
+ return;
4491
+ }
4492
+ res.statusCode = 200;
4493
+ res.setHeader('Content-Type', 'audio/wav');
4494
+ res.setHeader('Cache-Control', 'public, max-age=86400');
4495
+ res.end(bytes);
4496
+ }
4497
+
4095
4498
  /** POST /pet-chat/voice/packs/default { id } —— 设为全局默认音色。 */
4096
4499
  async function handleVoicePackDefault(req, res) {
4097
4500
  let body = {};
@@ -4478,9 +4881,9 @@ async function handleMicTest(req, res) {
4478
4881
  };
4479
4882
  }
4480
4883
  const lyricLines = Array.isArray(args.lyrics)
4481
- ? args.lyrics
4884
+ ? args.lyrics.map((line) => sanitizeLyrics(line)).filter(Boolean)
4482
4885
  : (typeof args.lyrics === 'string' && args.lyrics.trim()
4483
- ? String(args.lyrics).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
4886
+ ? String(args.lyrics).split(/\r?\n/).map((line) => sanitizeLyrics(line)).filter(Boolean)
4484
4887
  : []);
4485
4888
  const plan = planSing({
4486
4889
  topic: String(args.topic || '今天').slice(0, 20),
@@ -4797,6 +5200,13 @@ async function handleMicTest(req, res) {
4797
5200
  if (tail === '/voice/packs/install' && method === 'POST') { await handleVoicePackInstall(req, res); return; }
4798
5201
  if (tail === '/voice/packs/remove' && method === 'POST') { await handleVoicePackRemove(req, res); return; }
4799
5202
  if (tail === '/voice/packs/default' && method === 'POST') { await handleVoicePackDefault(req, res); return; }
5203
+ // v1.2 用户音色包(角色语音走导入,不进 npm 包)+ 4 个内置系统音效
5204
+ if (tail === '/voice/user-packs' && (method === 'GET' || method === 'HEAD')) { handleUserVoicePacks(res); return; }
5205
+ if (tail === '/voice/user-packs/import' && method === 'POST') { await handleUserVoicePackImport(req, res); return; }
5206
+ if (tail === '/voice/user-packs/remove' && method === 'POST') { await handleUserVoicePackRemove(req, res); return; }
5207
+ if (tail === '/system-sounds' && (method === 'GET' || method === 'HEAD')) { handleSystemSounds(res); return; }
5208
+ const systemSoundMatch = /^\/system-sounds\/([^/]+\.wav)$/.exec(tail);
5209
+ if (systemSoundMatch && (method === 'GET' || method === 'HEAD')) { handleSystemSoundAudio(req, res, systemSoundMatch[1]); return; }
4800
5210
  if (tail === '/voice/preferred' && (method === 'GET' || method === 'HEAD' || method === 'POST')) { await handleVoicePreferred(req, res); return; }
4801
5211
  if (tail === '/voice/preview' && method === 'POST') { await handleVoicePreview(req, res); return; }
4802
5212
  if (tail === '/tts/preview' && method === 'POST') { await handleVoicePreview(req, res); return; }
@@ -4848,6 +5258,30 @@ if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatu
4848
5258
  return;
4849
5259
  }
4850
5260
  if (tail === '/proactive/tick' && method === 'POST') { await handleProactiveTick(req, res); return; }
5261
+ // v1.2 主动思维:没有外部事件时的“内心 tick”(默认关;勿扰/静默/忙碌时只说 record 或 none)
5262
+ if (tail === '/mind/tick' && method === 'POST') { await handleMindTick(req, res); return; }
5263
+ if (tail === '/mind/state' && (method === 'GET' || method === 'HEAD')) { handleMindState(res); return; }
5264
+ if (tail === '/mind/reset' && method === 'POST') {
5265
+ clearMindState();
5266
+ jsonSend(res, { ok: true });
5267
+ return;
5268
+ }
5269
+ // v1.2 屏幕感知 / 被动观察:默认关;关闭时连 PowerShell 都不启动
5270
+ if (tail === '/observe/status' && (method === 'GET' || method === 'HEAD')) { jsonSend(res, observeStatus()); return; }
5271
+ if (tail === '/observe/sample' && method === 'POST') { await handleObserveSample(req, res); return; }
5272
+ if (tail === '/observe/records' && (method === 'GET' || method === 'HEAD')) {
5273
+ const persona = getActivePersona();
5274
+ if (!persona) { jsonSend(res, { ok: false, code: 'no-persona', items: [] }); return; }
5275
+ const offset = Number(url.searchParams.get('offset') || 0);
5276
+ const limit = Number(url.searchParams.get('limit') || 50);
5277
+ jsonSend(res, { ok: true, personaId: persona.id, ...listObservations(persona.id, { offset, limit }) });
5278
+ return;
5279
+ }
5280
+ if (tail === '/observe/records' && method === 'DELETE') {
5281
+ const persona = getActivePersona();
5282
+ jsonSend(res, { ok: true, personaId: persona && persona.id, ...(persona ? clearObservations(persona.id) : { removed: 0 }) });
5283
+ return;
5284
+ }
4851
5285
  if (tail === '/silence' && method === 'POST') { await handleSilence(req, res); return; }
4852
5286
  if (tail === '/memory' && (method === 'GET' || method === 'HEAD')) {
4853
5287
  // 旧入口保留给气泡「查看记忆」;数据源已切到 active persona 的事件流,不再读旧 memory.json。
@@ -4878,8 +5312,12 @@ if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatu
4878
5312
  },
4879
5313
  }));
4880
5314
 
5315
+ // v1.2:屏幕感知采样(每 30 秒看一次设置;off 时不调用任何外部进程)
5316
+ startObserveLoop();
5317
+
4881
5318
  // 卸载:断开所有事件流 + 停掉懒启动的 TTS worker(不留后台进程)
4882
5319
  disposers.push(() => {
5320
+ if (observeTimer) { try { clearInterval(observeTimer); } catch { /* ignore */ } observeTimer = null; }
4883
5321
  pendingConfirms.clear();
4884
5322
  pendingConfirmById.clear();
4885
5323
  for (const hit of pendingClientActions.values()) {