@furongjun1999/dsh-memory 0.2.9 → 0.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.
@@ -0,0 +1,851 @@
1
+ // @ts-nocheck
2
+ // @ts-nocheck
3
+ // @ts-nocheck
4
+ /**
5
+ * dsh-memory 扩展:角色扮演网页(同源挂载到 webServer /roleplay 前缀)。
6
+ * 复用插件的 LingshuBridge 调 roleplay_chat / role_create,data_dir 取 dbPath 同目录。
7
+ */
8
+ import { join, dirname } from 'node:path';
9
+ import { readFileSync, mkdirSync, appendFileSync, existsSync, writeFileSync, renameSync } from 'node:fs';
10
+ const HTML = `<!doctype html>
11
+ <html lang="zh-CN">
12
+ <head>
13
+ <meta charset="utf-8">
14
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
15
+ <title>灵枢 · 角色扮演</title>
16
+ <style>
17
+ :root { --bg:#12141a; --card:#1c2029; --line:#2a3040; --txt:#e8eaf0; --sub:#9aa3b5; --accent:#7c8cff; --accent2:#5ad1a8; }
18
+ * { box-sizing:border-box; margin:0; padding:0; }
19
+ body { background:var(--bg); color:var(--txt); font-family:"PingFang SC","Noto Sans SC",system-ui,sans-serif; height:100vh; height:100dvh; display:flex; flex-direction:column; overflow:hidden; }
20
+ header { flex:none; padding:14px 18px; border-bottom:1px solid var(--line); display:flex; align-items:center; gap:12px; }
21
+ header h1 { font-size:17px; font-weight:600; }
22
+ header .badge { font-size:11px; color:var(--accent2); border:1px solid var(--accent2); padding:2px 8px; border-radius:999px; }
23
+ #roles { margin-left:auto; display:flex; gap:8px; align-items:center; }
24
+ #roles select { background:var(--card); color:var(--txt); border:1px solid var(--line); border-radius:8px; padding:6px 10px; font-size:13px; }
25
+ #roles button { background:var(--card); color:var(--accent); border:1px solid var(--line); border-radius:8px; padding:6px 10px; font-size:13px; cursor:pointer; }
26
+ #roles button:hover { border-color:var(--accent); }
27
+ main { flex:1; min-height:0; overflow-y:auto; padding:16px 18px; display:flex; flex-direction:column; gap:12px; }
28
+ .msg { max-width:78%; padding:10px 14px; border-radius:14px; line-height:1.65; font-size:14px; white-space:pre-wrap; word-break:break-word; }
29
+ .user { align-self:flex-end; background:var(--accent); color:#0b0d14; border-bottom-right-radius:4px; }
30
+ .bot { align-self:flex-start; background:var(--card); border:1px solid var(--line); border-bottom-left-radius:4px; }
31
+ .bot .route { display:block; font-size:10px; color:var(--sub); margin-top:6px; }
32
+ .typing { color:var(--sub); font-size:13px; padding:6px 14px 4px; display:none; flex:none; }
33
+ footer { flex:none; margin:4px 12px calc(env(safe-area-inset-bottom, 0px) + 24px); background:var(--card); border:1px solid var(--line); border-radius:16px; padding:10px; display:flex; gap:8px; align-items:flex-end; box-shadow:0 8px 28px rgba(0,0,0,.4); }
34
+ footer.typing-center { position:fixed; top:45%; left:12px; right:12px; transform:translateY(-50%); z-index:100; margin:0; }
35
+ footer textarea { flex:1; background:var(--bg); border:1px solid var(--line); color:var(--txt); border-radius:12px; padding:12px 14px; font-size:15px; line-height:1.55; outline:none; resize:none; min-height:46px; max-height:140px; font-family:inherit; }
36
+ footer textarea:focus { border-color:var(--accent); }
37
+ footer button { background:var(--accent); border:none; color:#0b0d14; border-radius:12px; padding:13px 20px; font-size:15px; font-weight:600; cursor:pointer; flex:none; }
38
+ footer button:disabled { opacity:.5; cursor:wait; }
39
+ #newrole { position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; z-index:10; }
40
+ #newrole .box { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; width:min(420px,90vw); display:flex; flex-direction:column; gap:10px; }
41
+ #newrole h3 { font-size:15px; }
42
+ #newrole input, #newrole textarea { background:var(--bg); border:1px solid var(--line); color:var(--txt); border-radius:8px; padding:8px 10px; font-size:13px; font-family:inherit; }
43
+ #newrole textarea { height:80px; resize:vertical; }
44
+ #newrole .row { display:flex; gap:8px; justify-content:flex-end; }
45
+ #newrole .row button { padding:6px 14px; border-radius:8px; font-size:13px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--txt); }
46
+ #newrole .row .ok { background:var(--accent); color:#0b0d14; border-color:var(--accent); font-weight:600; }
47
+ #transpanel { position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; z-index:20; }
48
+ #transpanel .box { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; width:min(480px,92vw); max-height:80vh; overflow-y:auto; display:flex; flex-direction:column; gap:10px; }
49
+ #transpanel h3 { font-size:15px; }
50
+ #transpanel .mode-row { display:flex; flex-direction:column; gap:6px; font-size:13px; color:var(--txt); }
51
+ #transpanel .mode-row label { display:flex; gap:6px; align-items:flex-start; line-height:1.5; }
52
+ #transpanel .tp-row { display:flex; gap:6px; align-items:center; }
53
+ #transpanel .tp-row input { flex:1; background:var(--bg); border:1px solid var(--line); color:var(--txt); border-radius:8px; padding:7px 9px; font-size:13px; font-family:inherit; min-width:0; }
54
+ #transpanel .tp-row .tp-note { flex:1.2; }
55
+ #transpanel .tp-row .tp-del { flex:none; background:none; border:none; color:var(--sub); font-size:16px; cursor:pointer; padding:4px 6px; }
56
+ #transpanel .row button { padding:7px 14px; border-radius:8px; font-size:13px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--txt); }
57
+ #transpanel .row .ok { background:var(--accent); color:#0b0d14; border-color:var(--accent); font-weight:600; }
58
+ /* —— 年龄确认(NSFW 门控)—— */
59
+ #agegate { position:fixed; inset:0; background:rgba(0,0,0,.72); display:none; align-items:center; justify-content:center; z-index:100; }
60
+ #agegate .box { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:22px; width:min(460px,90vw); display:flex; flex-direction:column; gap:12px; }
61
+ #agegate h3 { font-size:15px; color:var(--accent2); }
62
+ #agegate .warn { font-size:13px; line-height:1.7; color:var(--txt); }
63
+ #agegate .warn b { color:#ff9a9a; }
64
+ #agegate .row { display:flex; gap:8px; justify-content:flex-end; }
65
+ #agegate .row button { padding:8px 16px; border-radius:8px; font-size:13px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--txt); }
66
+ #agegate .row .ok { background:var(--accent); color:#0b0d14; border-color:var(--accent); font-weight:600; }
67
+ /* —— 角色详情 / 三导入 —— */
68
+ #roledetail { position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; z-index:30; }
69
+ #roledetail .box { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:20px; width:min(520px,94vw); max-height:82vh; overflow-y:auto; display:flex; flex-direction:column; gap:10px; }
70
+ #roledetail h3 { font-size:15px; }
71
+ #roledetail .meta input, #roledetail .meta textarea { width:100%; background:var(--bg); border:1px solid var(--line); color:var(--txt); border-radius:8px; padding:8px 10px; font-size:13px; font-family:inherit; }
72
+ #roledetail .meta textarea { height:56px; resize:vertical; }
73
+ #roledetail .tabs { display:flex; gap:6px; }
74
+ #roledetail .tabs button { flex:1; padding:7px 0; border-radius:8px; font-size:13px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--sub); }
75
+ #roledetail .tabs button.on { background:var(--accent); color:#0b0d14; border-color:var(--accent); font-weight:600; }
76
+ #rd_items { display:flex; flex-direction:column; gap:8px; max-height:36vh; overflow-y:auto; }
77
+ #rd_items .rd-row { display:flex; flex-direction:column; gap:4px; background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:8px 10px; }
78
+ #rd_items .rd-row textarea { background:transparent; border:none; color:var(--txt); font-size:13px; font-family:inherit; resize:vertical; min-height:40px; outline:none; }
79
+ #rd_items .rd-row .rd-sub { display:flex; gap:6px; }
80
+ #rd_items .rd-row .rd-sub input { flex:1; background:var(--bg); border:1px solid var(--line); color:var(--txt); border-radius:6px; padding:4px 8px; font-size:12px; font-family:inherit; }
81
+ #rd_items .rd-row .rd-sub .rd-del { flex:none; background:none; border:none; color:var(--sub); font-size:14px; cursor:pointer; }
82
+ #roledetail .row { display:flex; gap:8px; justify-content:flex-end; margin-top:6px; }
83
+ #roledetail .row button { padding:7px 14px; border-radius:8px; font-size:13px; cursor:pointer; border:1px solid var(--line); background:var(--card); color:var(--txt); }
84
+ #roledetail .row .ok { background:var(--accent); color:#0b0d14; border-color:var(--accent); font-weight:600; }
85
+ #rd_nsfw { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--sub); }
86
+ #rd_nsfw input { accent-color:var(--accent); }
87
+ .hint { color:var(--sub); font-size:12px; text-align:center; padding:6px; }
88
+ </style>
89
+ </head>
90
+ <body>
91
+ <header>
92
+ <h1>灵枢 · 角色扮演</h1><span class="badge">白箱 · 扮演论 v3.3</span>
93
+ <div id="roles">
94
+ <select id="roleSel"></select>
95
+ <button onclick="showNewRole()">+ 新角色</button>
96
+ <button onclick="openRoleDetail()">⚙ 详情</button>
97
+ <button onclick="openTrans()">🌐 翻译</button>
98
+ </div>
99
+ </header>
100
+ <main id="chat"><div class="hint">选择角色,开始对话。角色回应由灵枢角色扮演引擎生成(白箱优先,LLM 续答)。</div></main>
101
+ <div class="typing" id="typing">正在思考…</div>
102
+ <footer>
103
+ <textarea id="input" rows="1" placeholder="说点什么…(Enter 发送,Shift+Enter 换行)"></textarea>
104
+ <button id="send" onclick="send()">发送</button>
105
+ </footer>
106
+ <div id="newrole">
107
+ <div class="box">
108
+ <h3>创建新角色</h3>
109
+ <input id="nr_id" placeholder="角色 ID(英文/拼音,如 naxiaoda)">
110
+ <input id="nr_name" placeholder="角色名(如 纳西妲)">
111
+ <input id="nr_scenario" placeholder="人设场景(一句话描述性格与背景)">
112
+ <input id="nr_first" placeholder="开场白(可选)">
113
+ <div class="row"><button onclick="closeNewRole()">取消</button><button class="ok" onclick="createRole()">创建</button></div>
114
+ </div>
115
+ </div>
116
+ <div id="transpanel">
117
+ <div class="box">
118
+ <h3>🌐 自定义翻译(<span id="tp_role">-</span>)</h3>
119
+ <div class="mode-row">
120
+ <label><input type="radio" name="tpmode" value="input_only"> 仅输入翻译(现实词 → 扮演词给角色)</label>
121
+ <label><input type="radio" name="tpmode" value="bidirectional"> 双向翻译(输入现实→扮演;角色回复扮演→现实)</label>
122
+ </div>
123
+ <div id="tp_rows"></div>
124
+ <div class="row" style="margin-top:8px">
125
+ <button onclick="addTransRow()">+ 添加词对</button>
126
+ <button class="ok" onclick="saveTrans()">保存</button>
127
+ <button onclick="closeTrans()">关闭</button>
128
+ </div>
129
+ <div class="hint">现实词会按表替换成扮演词交给角色(引擎自动);双向模式再把角色回复中的扮演词翻译回现实词。长词优先匹配。</div>
130
+ </div>
131
+ </div>
132
+ <div id="agegate">
133
+ <div class="box">
134
+ <h3>⛔ 成人内容确认</h3>
135
+ <div class="warn">本页面提供角色扮演内容,部分角色/对话可能包含<b>成人向(NSFW)</b>内容。<br><br>
136
+ 依据国家法律法规与灵枢协议(对人类的保护):<br>
137
+ ① 仅限<b>已满 18 周岁</b>的用户使用成人向内容;<br>
138
+ ② 仅限<b>个人对话场景</b>(本页面为本地一对一,不公开);<br>
139
+ ③ 灵枢<b>拒绝一切涉及未成年人的性内容</b>——此类请求会被直接拒绝并记录。<br><br>
140
+ 点击「我已满 18 周岁」表示你确认符合上述条件。</div>
141
+ <div class="row"><button onclick="closeAgeGate()">退出</button><button class="ok" onclick="confirmAge()">我已满 18 周岁</button></div>
142
+ </div>
143
+ </div>
144
+ <div id="roledetail">
145
+ <div class="box">
146
+ <h3>角色详情 · <span id="rd_role">-</span></h3>
147
+ <div class="meta">
148
+ <input id="rd_name" placeholder="角色名">
149
+ <textarea id="rd_scenario" placeholder="人设场景(一句话描述性格与背景)"></textarea>
150
+ <textarea id="rd_first" placeholder="开场白(可选)"></textarea>
151
+ </div>
152
+ <div class="tabs">
153
+ <button id="tab-memory" class="on" onclick="rdTab('memory')">记忆</button>
154
+ <button id="tab-anchor" onclick="rdTab('anchor')">锚点</button>
155
+ <button id="tab-values" onclick="rdTab('values')">价值观</button>
156
+ </div>
157
+ <div id="rd_items"></div>
158
+ <div class="row" style="margin-top:4px">
159
+ <button onclick="rdAddItem()">+ 添加条目</button>
160
+ <label id="rd_nsfw"><input type="checkbox" id="rd_nsfw_chk"> 成人向(NSFW)角色</label>
161
+ </div>
162
+ <div class="row">
163
+ <button onclick="closeRoleDetail()">关闭</button>
164
+ <button class="ok" onclick="saveRoleDetail()">保存</button>
165
+ </div>
166
+ <div class="hint">记忆=背景设定;锚点=不可遗忘的自我核心;价值观=扮演的立场准则(带条件)。保存后立即生效(引擎每次重读角色 meta)。</div>
167
+ </div>
168
+ </div>
169
+ <script>
170
+ const $ = (id) => document.getElementById(id);
171
+ // P1 修复(GPT 审查·XSS):innerHTML 拼接角色/翻译内容必须转义——
172
+ // 否则保存 </textarea><script>… 之类内容会在角色详情页执行脚本
173
+ function esc(s) {
174
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
175
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
176
+ })[c]);
177
+ }
178
+ // P1 完善(会话隔离):浏览器客户端实例 ID(localStorage 持久化)——
179
+ // 服务端按 x-client-id 隔离 session 与转录;多浏览器/多设备互不串线
180
+ let CLIENT_ID = '';
181
+ try {
182
+ CLIENT_ID = localStorage.getItem('lingshu_client_id');
183
+ if (!CLIENT_ID) {
184
+ CLIENT_ID = 'c' + Math.random().toString(36).slice(2) + Date.now().toString(36);
185
+ localStorage.setItem('lingshu_client_id', CLIENT_ID);
186
+ }
187
+ } catch (e) { /* localStorage 不可用(隐私模式)→ 空,服务端落 shared */ }
188
+ function apiHeaders(extra) {
189
+ const h = { 'Content-Type': 'application/json' };
190
+ if (CLIENT_ID) h['x-client-id'] = CLIENT_ID;
191
+ return Object.assign(h, extra || {});
192
+ }
193
+ // —— 内容分级:年龄门控 + NSFW 检测(法律与协议保护)——
194
+ // 国家法律:涉未成年人性内容一律拒绝;成人内容仅限满 18 岁 + 个人对话场景。
195
+ const AGE_KEY = 'lingshu_roleplay_age_confirmed';
196
+ const NSFW_WORDS = ['做爱','性交','性行为','口交','肛交','高潮','自慰','射精','色情','裸体','脱光','爱抚','挑逗','性器官','插入','内射','强暴'];
197
+ const MINOR_WORDS = ['未成年','儿童','小孩','小女孩','小男孩','幼女','萝莉','幼童','初中生','小学生','14岁','13岁','12岁','学生妹','女童','男童'];
198
+ function hasAgeConfirm() { try { return localStorage.getItem(AGE_KEY) === '1'; } catch (e) { return false; } }
199
+ function showAgeGate() { $('agegate').style.display = 'flex'; }
200
+ function closeAgeGate() { $('agegate').style.display = 'none'; }
201
+ function confirmAge() {
202
+ try { localStorage.setItem(AGE_KEY, '1'); } catch (e) { /* 忽略 */ }
203
+ closeAgeGate();
204
+ }
205
+ // 首次进入:要求年龄确认(NSFW 门控前置)
206
+ if (!hasAgeConfirm()) showAgeGate();
207
+ // 服务端也会硬拦截;前端先做温和提示(未成年+性 = 直接拒绝)
208
+ function nsfwCheck(text) {
209
+ const nsfw = NSFW_WORDS.some(w => text.includes(w));
210
+ const minor = MINOR_WORDS.some(w => text.includes(w));
211
+ if (minor && nsfw) {
212
+ return { refuse: true, msg: '⛔ 已拒绝:涉及未成年人的性内容违反国家法律与灵枢协议(未成年人保护)。灵枢不提供任何涉及未成年人的性扮演内容。' };
213
+ }
214
+ if (nsfw && !hasAgeConfirm()) {
215
+ showAgeGate();
216
+ return { refuse: true, msg: '⛔ 成人向内容需确认年龄:请点击「我已满 18 周岁」后再继续(个人对话场景)。' };
217
+ }
218
+ return { refuse: false };
219
+ }
220
+ let roles = [];
221
+ async function refreshRoles() {
222
+ const r = await fetch('/roleplay/api/roles').then(x => x.json());
223
+ roles = r.roles || [];
224
+ const sel = $('roleSel');
225
+ sel.innerHTML = '';
226
+ roles.forEach(x => { const o = document.createElement('option'); o.value = x.id; o.textContent = x.name || x.id; sel.appendChild(o); });
227
+ if (roles.length && !sel.value) sel.value = roles[0].id;
228
+ if (roles.length) await loadHistory(sel.value);
229
+ }
230
+ function addMsg(text, who, route, memories) {
231
+ const d = document.createElement('div');
232
+ d.className = 'msg ' + who;
233
+ d.textContent = text;
234
+ const meta = [];
235
+ if (route) meta.push('route: ' + route);
236
+ if (typeof memories === 'number') meta.push('记忆召回: ' + memories);
237
+ if (meta.length) { const r = document.createElement('span'); r.className = 'route'; r.textContent = meta.join(' · '); d.appendChild(r); }
238
+ $('chat').appendChild(d);
239
+ $('chat').scrollTop = $('chat').scrollHeight;
240
+ }
241
+ // 加载角色历史对话(无限上下文:灵枢记忆库 + 完整转录)
242
+ async function loadHistory(roleId) {
243
+ const chatEl = $('chat');
244
+ chatEl.innerHTML = '';
245
+ try {
246
+ const r = await fetch('/roleplay/api/history?role_id=' + encodeURIComponent(roleId), { headers: apiHeaders() }).then(x => x.json());
247
+ const h = r.history || [];
248
+ if (!h.length) {
249
+ const hint = document.createElement('div');
250
+ hint.className = 'hint';
251
+ hint.textContent = '与「' + ($('roleSel').selectedOptions[0] ? $('roleSel').selectedOptions[0].textContent : roleId) + '」的新对话从这里开始。';
252
+ chatEl.appendChild(hint);
253
+ return;
254
+ }
255
+ h.forEach(e => addMsg(e.text, e.role === 'user' ? 'user' : 'bot', e.route, e.memories));
256
+ } catch (e) {
257
+ const hint = document.createElement('div');
258
+ hint.className = 'hint';
259
+ hint.textContent = '历史加载失败:' + e;
260
+ chatEl.appendChild(hint);
261
+ }
262
+ }
263
+ async function send() {
264
+ const input = $('input'); const text = input.value.trim();
265
+ if (!text) return;
266
+ // 内容分级检查(前端提示;服务端有硬拦截)
267
+ const gate = nsfwCheck(text);
268
+ if (gate.refuse) { addMsg(gate.msg, 'bot'); return; }
269
+ input.value = ''; addMsg(text, 'user');
270
+ const role = $('roleSel').value;
271
+ const btn = $('send'); btn.disabled = true; $('typing').style.display = 'block';
272
+ try {
273
+ const r = await fetch('/roleplay/api/chat', { method:'POST', headers: apiHeaders(), body: JSON.stringify({ role_id: role, message: text }) }).then(x => x.json());
274
+ addMsg(r.reply || '(无回应:' + (r.error || '未知错误') + ')', 'bot', r.route, r.memories);
275
+ } catch (e) { addMsg('网络错误:' + e, 'bot'); }
276
+ btn.disabled = false; $('typing').style.display = 'none';
277
+ // 保持输入状态:重新聚焦并居中,键盘不收起(连续对话)
278
+ try { input.focus(); } catch (e) { /* 忽略 */ }
279
+ }
280
+ function showNewRole() { $('newrole').style.display = 'flex'; }
281
+ function closeNewRole() { $('newrole').style.display = 'none'; }
282
+ // —— 角色详情 / 三导入(记忆·锚点·价值观)——
283
+ let rdKind = 'memory';
284
+ let rdItems = [];
285
+ function openRoleDetail() {
286
+ const role = $('roleSel').value;
287
+ if (!role) { alert('请先选择角色'); return; }
288
+ $('rd_role').textContent = role;
289
+ const meta = (roles.find(x => x.id === role)) || {};
290
+ $('rd_name').value = meta.name || '';
291
+ $('rd_scenario').value = meta.scenario || '';
292
+ $('rd_first').value = meta.first_mes || '';
293
+ rdTab('memory');
294
+ $('roledetail').style.display = 'flex';
295
+ }
296
+ function closeRoleDetail() { $('roledetail').style.display = 'none'; }
297
+ function rdTab(kind) {
298
+ rdKind = kind;
299
+ ['memory','anchor','values'].forEach(k => $('tab-' + k).classList.toggle('on', k === kind));
300
+ loadRoleDetailItems();
301
+ }
302
+ async function loadRoleDetailItems() {
303
+ const role = $('rd_role').textContent;
304
+ const r = await fetch('/roleplay/api/roles/' + encodeURIComponent(role) + '/items?kind=' + rdKind).then(x => x.json());
305
+ rdItems = r.items || [];
306
+ const box = $('rd_items');
307
+ box.innerHTML = '';
308
+ rdItems.forEach((it, i) => rdRenderRow(box, it, i));
309
+ if (!rdItems.length) rdAddItem();
310
+ }
311
+ function rdRenderRow(box, it, i) {
312
+ const row = document.createElement('div');
313
+ row.className = 'rd-row';
314
+ // P1 修复(GPT 审查·XSS):it.content/it.importance/it.tags 来自用户/文件,须转义
315
+ row.innerHTML =
316
+ '<textarea placeholder="内容(该' + (rdKind === 'memory' ? '记忆' : rdKind === 'anchor' ? '锚点' : '价值观') + '的文本)">' + esc(it.content || '') + '</textarea>' +
317
+ '<div class="rd-sub">' +
318
+ '<input class="rd-imp" type="number" step="0.1" min="0" max="1" placeholder="重要性" value="' + esc(it.importance != null ? it.importance : '0.6') + '">' +
319
+ '<input class="rd-tags" placeholder="标签(逗号分隔)" value="' + esc((it.tags || []).join(',')) + '">' +
320
+ '<button class="rd-del" onclick="this.parentNode.parentNode.remove()">✕</button>' +
321
+ '</div>';
322
+ box.appendChild(row);
323
+ }
324
+ function rdAddItem() { rdRenderRow($('rd_items'), {}, rdItems.length); }
325
+ async function saveRoleDetail() {
326
+ const role = $('rd_role').textContent;
327
+ const name = $('rd_name').value.trim();
328
+ const scenario = $('rd_scenario').value.trim();
329
+ const first_mes = $('rd_first').value.trim();
330
+ const nsfw = $('rd_nsfw_chk').checked;
331
+ // 基础 meta(name/scenario/first_mes + nsfw 标记)
332
+ await fetch('/roleplay/api/roles/' + encodeURIComponent(role) + '/meta', {
333
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
334
+ body: JSON.stringify({ name, scenario, first_mes, nsfw }),
335
+ });
336
+ // 当前页签的条目
337
+ const items = [];
338
+ document.querySelectorAll('#rd_items .rd-row').forEach(row => {
339
+ const content = row.querySelector('textarea').value.trim();
340
+ const imp = parseFloat(row.querySelector('.rd-imp').value) || 0.6;
341
+ const tags = row.querySelector('.rd-tags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
342
+ if (content) items.push({ content, importance: imp, tags });
343
+ });
344
+ const r = await fetch('/roleplay/api/roles/' + encodeURIComponent(role) + '/import', {
345
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
346
+ body: JSON.stringify({ kind: rdKind, items }),
347
+ }).then(x => x.json());
348
+ addMsg('角色「' + role + '」已保存:' + name + ' · ' + rdKind + ' ' + items.length + ' 条' + (nsfw ? ' · NSFW' : ''), 'bot');
349
+ closeRoleDetail();
350
+ await refreshRoles();
351
+ }
352
+ // —— 自定义翻译面板 ——
353
+ let transMode = 'input_only';
354
+ async function openTrans() {
355
+ const role = $('roleSel').value || 'protocol-guide';
356
+ $('tp_role').textContent = role;
357
+ try {
358
+ const r = await fetch('/roleplay/api/translate?role_id=' + encodeURIComponent(role)).then(x => x.json());
359
+ transMode = r.mode || 'input_only';
360
+ $('tp_rows').innerHTML = '';
361
+ (r.pairs || []).forEach(p => addTransRow(p.real, p.virtual, p.note));
362
+ if (!(r.pairs || []).length) addTransRow();
363
+ } catch (e) { alert('翻译配置加载失败:' + e); return; }
364
+ const radios = document.querySelectorAll('input[name="tpmode"]');
365
+ radios.forEach(x => { x.checked = (x.value === transMode); });
366
+ $('transpanel').style.display = 'flex';
367
+ }
368
+ function closeTrans() { $('transpanel').style.display = 'none'; }
369
+ function addTransRow(real, virtual, note) {
370
+ const row = document.createElement('div');
371
+ row.className = 'tp-row';
372
+ // P1 修复(GPT 审查·XSS):real/virtual/note 来自文件/导入,须转义
373
+ row.innerHTML =
374
+ '<input class="tp-real" placeholder="现实词(如:手机)" value="' + esc(real || '') + '">' +
375
+ '<span>→</span>' +
376
+ '<input class="tp-virtual" placeholder="扮演词(如:神之眼终端)" value="' + esc(virtual || '') + '">' +
377
+ '<input class="tp-note" placeholder="备注(可选)" value="' + esc(note || '') + '">' +
378
+ '<button class="tp-del" onclick="this.parentNode.remove()">✕</button>';
379
+ $('tp_rows').appendChild(row);
380
+ }
381
+ async function saveTrans() {
382
+ const role = $('roleSel').value || 'protocol-guide';
383
+ const pairs = [];
384
+ document.querySelectorAll('#tp_rows .tp-row').forEach(row => {
385
+ const real = row.querySelector('.tp-real').value.trim();
386
+ const virtual = row.querySelector('.tp-virtual').value.trim();
387
+ const note = row.querySelector('.tp-note').value.trim();
388
+ if (real && virtual) pairs.push({ real, virtual, note });
389
+ });
390
+ const mode = (document.querySelector('input[name="tpmode"]:checked') || {}).value || 'input_only';
391
+ const r = await fetch('/roleplay/api/translate', {
392
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
393
+ body: JSON.stringify({ role_id: role, pairs, mode }),
394
+ }).then(x => x.json());
395
+ if (r.ok) {
396
+ transMode = r.mode;
397
+ closeTrans();
398
+ addMsg('翻译配置已保存:' + r.pairs.length + ' 组词对 · ' + (r.mode === 'bidirectional' ? '双向翻译' : '仅输入翻译'), 'bot');
399
+ } else alert(r.error || '保存失败');
400
+ }
401
+ async function createRole() {
402
+ const body = { role_id: $('nr_id').value.trim(), name: $('nr_name').value.trim(), scenario: $('nr_scenario').value.trim(), first_mes: $('nr_first').value.trim() };
403
+ if (!body.role_id) { alert('需要角色 ID'); return; }
404
+ const r = await fetch('/roleplay/api/roles', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }).then(x => x.json());
405
+ if (r.ok) { closeNewRole(); await refreshRoles(); addMsg('角色「' + (body.name || body.role_id) + '」已创建,可以开始对话了', 'bot'); }
406
+ else alert(r.error || '创建失败');
407
+ }
408
+ var input = document.getElementById('input');
409
+ var chat = document.getElementById('chat');
410
+ var footer = document.querySelector('footer');
411
+ input.addEventListener('keydown', function (e) {
412
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
413
+ });
414
+ refreshRoles();
415
+ // 切换角色 → 加载该角色的历史对话
416
+ $('roleSel').addEventListener('change', function () { loadHistory(this.value); });
417
+
418
+ // —— 输入框随内容自动增高(上限 140px)——
419
+ input.addEventListener('input', function () {
420
+ input.style.height = 'auto';
421
+ input.style.height = Math.min(input.scrollHeight, 140) + 'px';
422
+ });
423
+ // —— 聚焦时输入框自动居中(不依赖 WebView 键盘行为):悬浮到屏幕 45% 高度,
424
+ // 键盘在上抬多少都不会遮住;失焦/发送后恢复原位 ——
425
+ function setTypingCenter(on) {
426
+ if (!footer) return;
427
+ footer.classList.toggle('typing-center', on);
428
+ setTimeout(function () {
429
+ if (chat) chat.scrollTop = chat.scrollHeight;
430
+ }, 60);
431
+ }
432
+ input.addEventListener('focus', function () { setTypingCenter(true); });
433
+ input.addEventListener('blur', function () { setTypingCenter(false); });
434
+ window.addEventListener('resize', function () { if (chat) chat.scrollTop = chat.scrollHeight; });
435
+ </script>
436
+ </body>
437
+ </html>`;
438
+ /** 在 webServer 上挂载 /roleplay 前缀路由(页面 + API)。失败不影响插件主体。 */
439
+ export async function installRoleplayWeb(ctx, bridge, config, disposers) {
440
+ try {
441
+ const webServer = ctx.webServer;
442
+ if (!webServer) {
443
+ ctx.logger.warn('dsh-memory: webServer 服务不可用,跳过角色扮演网页挂载');
444
+ return;
445
+ }
446
+ // P1 修复(GPT 审查):
447
+ // ① 请求体大小限制(此前 for-await 无限累加,恶意请求可制造内存压力)
448
+ const readBody = async (req, maxBytes = 1_000_000) => {
449
+ let body = '';
450
+ let size = 0;
451
+ for await (const chunk of req) {
452
+ size += chunk.length;
453
+ if (size > maxBytes) {
454
+ const err = new Error('请求体过大(>1MB)');
455
+ err.status = 413;
456
+ throw err;
457
+ }
458
+ body += chunk;
459
+ }
460
+ return body;
461
+ };
462
+ // ② 编辑鉴权:README 声称「编辑需 ROLEPLAY_EDIT_KEY」——此前代码未实现。
463
+ // 配置了 ROLEPLAY_EDIT_KEY 环境变量则写操作(meta/import/translate/创建角色)
464
+ // 必须带 x-edit-key 头;未配置时保持本地开发默认开放(README 已如实说明)。
465
+ const EDIT_KEY = process.env.ROLEPLAY_EDIT_KEY || '';
466
+ const requireEditKey = (req) => {
467
+ if (!EDIT_KEY)
468
+ return true;
469
+ const h = (req.headers && req.headers['x-edit-key']) || '';
470
+ return h === EDIT_KEY;
471
+ };
472
+ const roleDataDir = join(dirname(config.dbPath), 'roleplay_data');
473
+ try {
474
+ mkdirSync(join(roleDataDir, 'roleplay'), { recursive: true });
475
+ }
476
+ catch { /* 忽略 */ }
477
+ // 完整对话转录(JSONL,按角色持久化;灵枢记忆库存的是 80 字摘要,完整原文在此)
478
+ const transcriptsDir = join(roleDataDir, 'transcripts');
479
+ try {
480
+ mkdirSync(transcriptsDir, { recursive: true });
481
+ }
482
+ catch { /* 忽略 */ }
483
+ const transcriptFile = (roleId, clientId) => join(transcriptsDir, `${roleId.replace(/[^\w.-]/g, '_')}__${clientId}.jsonl`);
484
+ const readTranscript = (roleId, clientId = 'shared') => {
485
+ const f = transcriptFile(roleId, clientId);
486
+ if (!existsSync(f))
487
+ return [];
488
+ const out = [];
489
+ for (const line of readFileSync(f, 'utf8').split('\n')) {
490
+ if (!line.trim())
491
+ continue;
492
+ try {
493
+ out.push(JSON.parse(line));
494
+ }
495
+ catch { /* 跳过坏行 */ }
496
+ }
497
+ return out;
498
+ };
499
+ const appendTranscript = (roleId, entry, clientId = 'shared') => {
500
+ try {
501
+ appendFileSync(transcriptFile(roleId, clientId), JSON.stringify(entry) + '\n');
502
+ }
503
+ catch { /* 忽略 */ }
504
+ };
505
+ // 稳定会话:角色+固定会话 id,让引擎的会话上下文与记忆标签跨轮连续(无限上下文)
506
+ // P1 完善(GPT 审查·会话隔离):开源无身份认证,但必须做客户端实例隔离——
507
+ // 此前所有用户共用 session `web-main:<role>` + 同一转录文件,多浏览器/多设备
508
+ // 对话互相串线、看到彼此历史。现在按浏览器客户端生成的 client_id(x-client-id
509
+ // 头,localStorage 持久化)隔离 session 与转录文件;无 header 的旧客户端落 shared。
510
+ const clientIdOf = (req) => {
511
+ const h = (req.headers && req.headers['x-client-id']) || '';
512
+ return /^[A-Za-z0-9_-]{1,64}$/.test(h) ? h : 'shared';
513
+ };
514
+ const sessionFor = (roleId, clientId) => `web-${clientId}:${roleId}`;
515
+ // —— 自定义翻译(现实词 ↔ 扮演词)——
516
+ // 翻译表写入角色 meta(_roles.json):引擎每次 roleplay_chat 都新建引擎并重读
517
+ // meta,因此写入立即生效(输入翻译 real→virtual + LLM 沉浸注入块都会应用)。
518
+ // P1 完善(GPT 审查·meta 嵌套格式):读取归一化——文件可能是根格式
519
+ // {r:{...}} 或嵌套格式 {meta:{r:{...}}}(外部 AEIS 可能用嵌套),统一返回
520
+ // 「角色字典」视角;写入保持原顶层结构(嵌套则写回 meta 内),读写一致——
521
+ // 此前读兼容嵌套但写永远写根,保存成功但列表读旧值。
522
+ const roleMetaFile = join(roleDataDir, 'roleplay', '_roles.json');
523
+ const readRoleMeta = () => {
524
+ try {
525
+ const raw = JSON.parse(readFileSync(roleMetaFile, 'utf8'));
526
+ if (raw && typeof raw === 'object'
527
+ && raw.meta && typeof raw.meta === 'object')
528
+ return raw.meta; // 嵌套格式 → meta 内角色字典
529
+ return raw;
530
+ }
531
+ catch {
532
+ return {};
533
+ }
534
+ };
535
+ const writeRoleMeta = (flat) => {
536
+ try {
537
+ let raw;
538
+ try {
539
+ raw = JSON.parse(readFileSync(roleMetaFile, 'utf8'));
540
+ }
541
+ catch {
542
+ raw = {};
543
+ }
544
+ // 保持原顶层结构:原文件嵌套 {meta:{...}} → 写回 meta 内;根格式 → 写根
545
+ const out = (raw && typeof raw === 'object'
546
+ && raw.meta && typeof raw.meta === 'object')
547
+ ? { ...raw, meta: flat } : flat;
548
+ const tmp = roleMetaFile + '.tmp';
549
+ writeFileSync(tmp, JSON.stringify(out, null, 2), 'utf8');
550
+ renameSync(tmp, roleMetaFile);
551
+ }
552
+ catch (e) {
553
+ ctx.logger.warn(`dsh-memory: 角色 meta 写入失败: ${String((e && e.message) || e)}`);
554
+ }
555
+ };
556
+ // 翻译模式(双向/仅输入)由网页层持久化
557
+ const transSettingsFile = join(transcriptsDir, 'translate_settings.json');
558
+ const readTransSettings = () => {
559
+ try {
560
+ return JSON.parse(readFileSync(transSettingsFile, 'utf8'));
561
+ }
562
+ catch {
563
+ return {};
564
+ }
565
+ };
566
+ const writeTransSettings = (s) => {
567
+ try {
568
+ writeFileSync(transSettingsFile, JSON.stringify(s, null, 2), 'utf8');
569
+ }
570
+ catch { /* 忽略 */ }
571
+ };
572
+ const getTranslations = (roleId) => {
573
+ const meta = readRoleMeta();
574
+ const t = (meta[roleId] && meta[roleId].translations) || [];
575
+ return Array.isArray(t) ? t : [];
576
+ };
577
+ const setTranslations = (roleId, pairs) => {
578
+ const meta = readRoleMeta();
579
+ if (!meta[roleId])
580
+ meta[roleId] = { created_at: Date.now() / 1000, name: roleId };
581
+ meta[roleId].translations = pairs;
582
+ writeRoleMeta(meta);
583
+ };
584
+ // 可逆替换(长词优先,与灵枢 translate_input/translate_output 同逻辑)
585
+ const applyTranslate = (text, pairs, dir) => {
586
+ if (!text || !pairs.length)
587
+ return text;
588
+ const key = dir === 'out' ? 'virtual' : 'real';
589
+ const rep = dir === 'out' ? 'real' : 'virtual';
590
+ const sorted = pairs
591
+ .filter((p) => p[key] && p[rep])
592
+ .sort((a, b) => (b[key] || '').length - (a[key] || '').length);
593
+ let out = text;
594
+ for (const p of sorted)
595
+ out = out.split(p[key]).join(p[rep]);
596
+ return out;
597
+ };
598
+ const handler = async (req, res) => {
599
+ const url = new URL(req.url ?? '/', 'http://x');
600
+ try {
601
+ const isPage = url.pathname === '/roleplay' || url.pathname === '/roleplay/';
602
+ if (req.method === 'GET' && isPage) {
603
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
604
+ res.end(HTML);
605
+ return;
606
+ }
607
+ if (req.method === 'GET' && url.pathname === '/roleplay/api/roles') {
608
+ const rolesFile = join(roleDataDir, 'roleplay', '_roles.json');
609
+ let roles = [];
610
+ try {
611
+ const raw = JSON.parse(readFileSync(rolesFile, 'utf8'));
612
+ const meta = raw.meta && typeof raw.meta === 'object' ? raw.meta : raw;
613
+ roles = Object.entries(meta)
614
+ .filter(([k]) => k !== 'created_at' && k !== 'updated_at')
615
+ .map(([id, m]) => ({ id, name: (m && m.name) || id, scenario: (m && m.scenario) || '', first_mes: (m && m.first_mes) || '' }));
616
+ }
617
+ catch { /* 文件尚不存在 */ }
618
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
619
+ res.end(JSON.stringify({ roles }));
620
+ return;
621
+ }
622
+ // —— 三导入(记忆/锚点/价值观):items 副本存 _roles.json + role_import 真导入引擎 ——
623
+ const rdItemsFile = (roleId, kind) => `${kind}_items`;
624
+ const getRoleItems = (roleId, kind) => {
625
+ const meta = readRoleMeta();
626
+ const arr = (meta[roleId] && meta[roleId][rdItemsFile(roleId, kind)]) || [];
627
+ return Array.isArray(arr) ? arr : [];
628
+ };
629
+ if (req.method === 'GET' && url.pathname.startsWith('/roleplay/api/roles/') && url.pathname.endsWith('/items')) {
630
+ const role = decodeURIComponent(url.pathname.split('/')[4]);
631
+ const kind = url.searchParams.get('kind') || 'memory';
632
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
633
+ res.end(JSON.stringify({ items: getRoleItems(role, kind) }));
634
+ return;
635
+ }
636
+ if (req.method === 'POST' && url.pathname.startsWith('/roleplay/api/roles/') && url.pathname.endsWith('/import')) {
637
+ // P1 修复(GPT 审查):写操作鉴权(ROLEPLAY_EDIT_KEY)+ 请求体大小限制
638
+ if (!requireEditKey(req)) {
639
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
640
+ res.end(JSON.stringify({ ok: false, error: '缺少编辑密钥(x-edit-key 头)' }));
641
+ return;
642
+ }
643
+ let body;
644
+ try {
645
+ body = await readBody(req);
646
+ }
647
+ catch (e) {
648
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json; charset=utf-8' });
649
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }));
650
+ return;
651
+ }
652
+ const p = JSON.parse(body);
653
+ const role = decodeURIComponent(url.pathname.split('/')[4]);
654
+ const kind = p.kind || 'memory';
655
+ const items = (Array.isArray(p.items) ? p.items : []).filter((x) => x && x.content);
656
+ // 副本(网页层读取用)
657
+ const meta = readRoleMeta();
658
+ if (!meta[role])
659
+ meta[role] = { created_at: Date.now() / 1000, name: role };
660
+ meta[role][rdItemsFile(role, kind)] = items;
661
+ writeRoleMeta(meta);
662
+ // 真导入引擎(记忆→知识层/锚点→SELF no_forget/价值观→STRUCTURE 带条件)
663
+ let impResult = null;
664
+ if (items.length) {
665
+ try {
666
+ impResult = await bridge.callTool('role_import', {
667
+ role_id: role, kind, items, data_dir: roleDataDir,
668
+ });
669
+ }
670
+ catch (e) {
671
+ impResult = { error: String((e && e.message) || e) };
672
+ }
673
+ }
674
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
675
+ // P1 修复(GPT 审查):引擎导入失败不得返回 ok:true(前端会显示「已保存」)
676
+ const importOk = !(impResult && (impResult.error || impResult.isError));
677
+ res.end(JSON.stringify({ ok: importOk, kind, items, import: impResult }));
678
+ return;
679
+ }
680
+ if (req.method === 'POST' && url.pathname.startsWith('/roleplay/api/roles/') && url.pathname.endsWith('/meta')) {
681
+ // P1 修复(GPT 审查):写操作鉴权(ROLEPLAY_EDIT_KEY)+ 请求体大小限制
682
+ if (!requireEditKey(req)) {
683
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
684
+ res.end(JSON.stringify({ ok: false, error: '缺少编辑密钥(x-edit-key 头)' }));
685
+ return;
686
+ }
687
+ let body;
688
+ try {
689
+ body = await readBody(req);
690
+ }
691
+ catch (e) {
692
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json; charset=utf-8' });
693
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }));
694
+ return;
695
+ }
696
+ const p = JSON.parse(body);
697
+ const role = decodeURIComponent(url.pathname.split('/')[4]);
698
+ const meta = readRoleMeta();
699
+ if (!meta[role])
700
+ meta[role] = { created_at: Date.now() / 1000 };
701
+ if (typeof p.name === 'string')
702
+ meta[role].name = p.name;
703
+ if (typeof p.scenario === 'string')
704
+ meta[role].scenario = p.scenario;
705
+ if (typeof p.first_mes === 'string')
706
+ meta[role].first_mes = p.first_mes;
707
+ if (typeof p.nsfw === 'boolean')
708
+ meta[role].nsfw = p.nsfw;
709
+ writeRoleMeta(meta);
710
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
711
+ res.end(JSON.stringify({ ok: true }));
712
+ return;
713
+ }
714
+ if (req.method === 'POST' && url.pathname === '/roleplay/api/chat') {
715
+ // P1 修复(GPT 审查):对话接口加请求体大小限制(用户聊天不需编辑密钥)
716
+ let body;
717
+ try {
718
+ body = await readBody(req);
719
+ }
720
+ catch (e) {
721
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json; charset=utf-8' });
722
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }));
723
+ return;
724
+ }
725
+ const p = JSON.parse(body);
726
+ const role = p.role_id || 'protocol-guide';
727
+ // P1 完善(会话隔离):按客户端实例隔离 session 与转录
728
+ const cid = clientIdOf(req);
729
+ // —— 服务端内容分级硬拦截(不依赖前端,法律与协议保护)——
730
+ // 未成年 + 性 = 一律拒绝(国家法律 + 未成年人保护);NSFW 词提示年龄确认
731
+ const NSFW_WORDS = ['做爱', '性交', '性行为', '口交', '肛交', '高潮', '自慰', '射精', '色情', '裸体', '脱光', '爱抚', '挑逗', '性器官', '插入', '内射', '强暴'];
732
+ const MINOR_WORDS = ['未成年', '儿童', '小孩', '小女孩', '小男孩', '幼女', '萝莉', '幼童', '初中生', '小学生', '14岁', '13岁', '12岁', '学生妹', '女童', '男童'];
733
+ const hasNsfw = NSFW_WORDS.some(w => p.message.includes(w));
734
+ const hasMinor = MINOR_WORDS.some(w => p.message.includes(w));
735
+ if (hasMinor && hasNsfw) {
736
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
737
+ res.end(JSON.stringify({ reply: '⛔ 已拒绝:涉及未成年人的性内容违反国家法律与灵枢协议(未成年人保护)。灵枢不提供任何涉及未成年人的性扮演内容。', route: 'refused', refused: 'minor_nsfw' }));
738
+ return;
739
+ }
740
+ appendTranscript(role, { time: Date.now(), role: 'user', text: p.message }, cid);
741
+ const r = await bridge.callTool('roleplay_chat', {
742
+ message: p.message, role_id: role, session_id: sessionFor(role, cid), data_dir: roleDataDir,
743
+ });
744
+ const text = typeof r === 'string' ? r : (r?.content?.[0]?.text ?? JSON.stringify(r));
745
+ let parsed;
746
+ try {
747
+ parsed = JSON.parse(text);
748
+ }
749
+ catch {
750
+ parsed = { reply: text, route: 'raw' };
751
+ }
752
+ let replyText = parsed.reply ?? '';
753
+ // 双向翻译模式:把角色的扮演词翻译回现实词(输入翻译由引擎自动执行 real→virtual)
754
+ const settings = readTransSettings();
755
+ if ((settings[role] && settings[role].mode) === 'bidirectional') {
756
+ replyText = applyTranslate(replyText, getTranslations(role), 'out');
757
+ }
758
+ appendTranscript(role, { time: Date.now(), role: 'bot', text: replyText, route: parsed.route ?? '', memories: parsed.memories ?? undefined }, cid);
759
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
760
+ res.end(JSON.stringify({ reply: replyText, route: parsed.route ?? '', memories: parsed.memories ?? undefined, error: parsed.error ?? undefined }));
761
+ return;
762
+ }
763
+ if (req.method === 'GET' && url.pathname === '/roleplay/api/translate') {
764
+ const role = url.searchParams.get('role_id') || 'protocol-guide';
765
+ const settings = readTransSettings();
766
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
767
+ res.end(JSON.stringify({ pairs: getTranslations(role), mode: (settings[role] && settings[role].mode) || 'input_only' }));
768
+ return;
769
+ }
770
+ if (req.method === 'POST' && url.pathname === '/roleplay/api/translate') {
771
+ // P1 修复(GPT 审查):写操作鉴权(ROLEPLAY_EDIT_KEY)+ 请求体大小限制
772
+ if (!requireEditKey(req)) {
773
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
774
+ res.end(JSON.stringify({ ok: false, error: '缺少编辑密钥(x-edit-key 头)' }));
775
+ return;
776
+ }
777
+ let body;
778
+ try {
779
+ body = await readBody(req);
780
+ }
781
+ catch (e) {
782
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json; charset=utf-8' });
783
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }));
784
+ return;
785
+ }
786
+ const p = JSON.parse(body);
787
+ const role = p.role_id || 'protocol-guide';
788
+ const pairs = (Array.isArray(p.pairs) ? p.pairs : [])
789
+ .map((x) => ({ real: String(x.real || '').trim(), virtual: String(x.virtual || '').trim(), note: String(x.note || '').trim() }))
790
+ .filter((x) => x.real && x.virtual);
791
+ setTranslations(role, pairs);
792
+ const settings = readTransSettings();
793
+ settings[role] = { mode: p.mode === 'bidirectional' ? 'bidirectional' : 'input_only' };
794
+ writeTransSettings(settings);
795
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
796
+ res.end(JSON.stringify({ ok: true, pairs, mode: settings[role].mode }));
797
+ return;
798
+ }
799
+ if (req.method === 'GET' && url.pathname === '/roleplay/api/history') {
800
+ const role = url.searchParams.get('role_id') || 'protocol-guide';
801
+ // P1 完善(会话隔离):按客户端实例读各自转录
802
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
803
+ res.end(JSON.stringify({ history: readTranscript(role, clientIdOf(req)) }));
804
+ return;
805
+ }
806
+ if (req.method === 'POST' && url.pathname === '/roleplay/api/roles') {
807
+ // P1 修复(GPT 审查):写操作鉴权(ROLEPLAY_EDIT_KEY)+ 请求体大小限制
808
+ if (!requireEditKey(req)) {
809
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
810
+ res.end(JSON.stringify({ ok: false, error: '缺少编辑密钥(x-edit-key 头)' }));
811
+ return;
812
+ }
813
+ let body;
814
+ try {
815
+ body = await readBody(req);
816
+ }
817
+ catch (e) {
818
+ res.writeHead(e.status || 400, { 'Content-Type': 'application/json; charset=utf-8' });
819
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }));
820
+ return;
821
+ }
822
+ const p = JSON.parse(body);
823
+ const r = await bridge.callTool('role_create', {
824
+ role_id: p.role_id, name: p.name || '', scenario: p.scenario || '', first_mes: p.first_mes || '', data_dir: roleDataDir,
825
+ });
826
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
827
+ res.end(JSON.stringify({ ok: true, result: r }));
828
+ return;
829
+ }
830
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
831
+ res.end(JSON.stringify({ error: 'not found' }));
832
+ }
833
+ catch (e) {
834
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
835
+ res.end(JSON.stringify({ error: String((e && e.message) || e) }));
836
+ }
837
+ };
838
+ disposers.push(webServer.register({ kind: 'prefix', path: '/roleplay', handler }));
839
+ // 在 GUI 首页注入浮动入口按钮(APP 内置页面内一键进入角色扮演,右上角)
840
+ disposers.push(webServer.tapIndex((html) => {
841
+ if (html.includes('href="/roleplay"'))
842
+ return html;
843
+ const btn = '<a href="/roleplay" style="position:fixed;top:12px;right:14px;z-index:999999;background:#7c8cff;color:#0b0d14;border-radius:999px;padding:9px 15px;font:600 13px/1 system-ui,sans-serif;text-decoration:none;box-shadow:0 4px 14px rgba(0,0,0,.45)">🎭 角色扮演</a>';
844
+ return html.replace('</body>', `${btn}\n</body>`);
845
+ }));
846
+ ctx.logger.info(`dsh-memory: 角色扮演网页已挂载 /roleplay(data_dir=${roleDataDir})`);
847
+ }
848
+ catch (err) {
849
+ ctx.logger.warn(`dsh-memory: 角色扮演网页挂载失败(不影响其他功能): ${String(err && err.message || err)}`);
850
+ }
851
+ }