pygmalion 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -0
- package/cordis.patch.yml +6 -0
- package/docs/ARCHITECTURE.md +107 -0
- package/docs/DEPLOY.md +129 -0
- package/docs/PRESET.md +59 -0
- package/package.json +32 -0
- package/preset/pygmalion-director/agent.cordis.yml +138 -0
- package/preset/pygmalion-director/preset.yml +3 -0
- package/preset/pygmalion-director/pygmalion-tools.js +20 -0
- package/src/active-session.js +64 -0
- package/src/agent-life.js +487 -0
- package/src/bot-factory.js +282 -0
- package/src/bots.js +273 -0
- package/src/config.js +67 -0
- package/src/dsh-bookkeeping.js +73 -0
- package/src/gateway.js +248 -0
- package/src/heartbeat.js +318 -0
- package/src/http-api.js +444 -0
- package/src/inbound.js +759 -0
- package/src/index.js +195 -0
- package/src/log.js +56 -0
- package/src/memory-write.js +133 -0
- package/src/outbound.js +392 -0
- package/src/persona.js +380 -0
- package/src/qqapi.js +420 -0
- package/src/refindex.js +83 -0
- package/src/session-log.js +140 -0
- package/src/setup-agent.js +96 -0
- package/src/slash-commands.js +142 -0
- package/src/store.js +155 -0
- package/src/threads.js +118 -0
- package/src/tools.js +500 -0
- package/src/types.js +19 -0
- package/src/wakeup.js +205 -0
- package/src/web-public/app.js +381 -0
- package/src/web-public/index.html +130 -0
- package/src/web-public/style.css +44 -0
- package/src/web-server.js +484 -0
- package/templates/sample-life.mjs +52 -0
package/src/wakeup.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pygmalion wakeup — the "唤醒 dsh 行动" engine.
|
|
3
|
+
*
|
|
4
|
+
* A scheduled script decides WHEN to wake up; this module makes the dsh agent
|
|
5
|
+
* ACT based on the real current situation. It does NOT send a preset message:
|
|
6
|
+
* it injects a situational [唤醒事件] context into the per-user agent session
|
|
7
|
+
* and wakes the driver, letting the director read memory / recent chat and
|
|
8
|
+
* decide whether (and what) to say. The agent's reply then flows out through
|
|
9
|
+
* the normal outbound pipeline; if the director chooses silence, nothing is
|
|
10
|
+
* sent and the decision can be written to memory.
|
|
11
|
+
*/
|
|
12
|
+
import { effectiveSessionId } from './inbound.js';
|
|
13
|
+
import { targetKey } from './threads.js';
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
|
|
16
|
+
|
|
17
|
+
/** Human "now" used inside the wakeup context. */
|
|
18
|
+
function nowText(now = new Date()) {
|
|
19
|
+
return now.toLocaleString('zh-CN', { hour12: false });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Build the model-facing wakeup context (reason + hint + memory pointers + persona name). */
|
|
23
|
+
export function buildWakeupContext({ reason, memoryHint, personaName, now = new Date() }) {
|
|
24
|
+
const parts = [
|
|
25
|
+
'[唤醒事件] 时间:' + nowText(now),
|
|
26
|
+
];
|
|
27
|
+
if (personaName != null && personaName.length > 0)
|
|
28
|
+
parts.push('角色:' + personaName);
|
|
29
|
+
parts.push('唤醒原因:' + (reason?.trim?.() ?? '计划时机已到'));
|
|
30
|
+
if (memoryHint != null && `${memoryHint}`.trim().length > 0)
|
|
31
|
+
parts.push('提示:' + `${memoryHint}`.trim());
|
|
32
|
+
parts.push('');
|
|
33
|
+
parts.push('你是被调度脚本按计划唤醒的。请作为导演:先读取工作区记忆与最近聊天,判断当');
|
|
34
|
+
parts.push('下真实情况(刚聊过什么?用户是否正在聊天?情境是否已变化?),再决定角色此刻');
|
|
35
|
+
parts.push('是否开口、说什么。可以顺势融入对话,也可以选择沉默。');
|
|
36
|
+
return parts.join('\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 归档任务情境:用户长时间未发言时,把原始记录按话题切片归档为双份记忆并建索引。 */
|
|
40
|
+
export function buildArchiveContext({ date, workspace, now = new Date() }) {
|
|
41
|
+
const parts = [
|
|
42
|
+
'[归档任务] 你的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
|
|
43
|
+
'时间:' + nowText(now),
|
|
44
|
+
'工作区:' + (workspace ?? ''),
|
|
45
|
+
];
|
|
46
|
+
if (date) parts.push('目标日期:' + date);
|
|
47
|
+
parts.push('');
|
|
48
|
+
parts.push('请完成记忆归档(这是后台维护,不是对用户说话——绝对不要调用 director_send):');
|
|
49
|
+
parts.push('1. 用文件工具读取 memory/<目标日期>/原始记录.md(系统已按时间归档的忠实原文);');
|
|
50
|
+
parts.push('2. 把聊天按「话题」切片进话题层:为每个话题创建目录 memory/topics/<具体话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/,写 原文.md 放该话题的原文;');
|
|
51
|
+
parts.push(' 目录名 = 具体话题 + 起止时刻(含日期、精确到秒,如 [2026-08-19 21:31:00-21:44:00],取该片段首尾消息时间;Windows 文件名不允许半角冒号,时间分隔一律用全角冒号「:」);');
|
|
52
|
+
parts.push(' 原文.md 必须逐字复制原始行——【绝对不要】用 write / str-replace-editor 重打内容(必然走样/转写);');
|
|
53
|
+
parts.push(' 要用 shell(Windows 用 pwsh)按行号把该话题覆盖的行【原样抽取】写入 原文.md:Get-Content 读原始记录、取对应行区间 Set-Content 到原文.md,写后读回核对与原始记录逐字一致;');
|
|
54
|
+
parts.push(' 话题边界由你自己读原文判定,不要按时间硬切、不要造兜底分组;');
|
|
55
|
+
parts.push('3. 每个话题目录里【必须】再写一份 索引.md(概要 / 关键事件 / 情感变化 / 待办与承诺);');
|
|
56
|
+
parts.push('4. 重写 memory/<目标日期>/索引.md,列出当日各话题、关键事件、情感变化、待办/承诺;');
|
|
57
|
+
parts.push('5. 若某片段是「对 TA 的印象 / TA 的重要事件 / 值得记住的事」,顺手把要点更新进 memory/关于TA.md;');
|
|
58
|
+
parts.push('6. 全部写完后再遍历 memory/topics/ 下每个目录自查:每个目录必须同时含 原文.md 与 索引.md,且 原文.md 与原始记录对应行逐字一致,缺/错则补正;若当日已归档或无需归档,跳过并在最终文本里说明即可。');
|
|
59
|
+
return parts.join('\n');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 「脚本事件」情境:角色的生活脚本报来一个生活事件(想 ta、心情变化、突发小事件),
|
|
64
|
+
* 唤醒导演判断此刻是否由角色开口。脚本侧一行 wake() 即可触发。
|
|
65
|
+
*/
|
|
66
|
+
export function buildScriptEventContext({ event, mood, topic, reason, personaName, now = new Date() }) {
|
|
67
|
+
const parts = [
|
|
68
|
+
'[脚本事件] 时间:' + nowText(now),
|
|
69
|
+
];
|
|
70
|
+
if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
|
|
71
|
+
if (reason != null && `${reason}`.trim()) parts.push('触发:' + `${reason}`.trim());
|
|
72
|
+
parts.push('');
|
|
73
|
+
parts.push('你的生活脚本报来一个角色生活事件(脚本模拟产生):');
|
|
74
|
+
if (event != null && `${event}`.trim()) parts.push('· 事件:' + event);
|
|
75
|
+
if (mood != null && `${mood}`.trim()) parts.push('· 心情:' + mood);
|
|
76
|
+
if (topic != null && `${topic}`.trim()) parts.push('· 主题:' + topic);
|
|
77
|
+
parts.push('');
|
|
78
|
+
parts.push('这是角色聊天之外的独立生活中真实发生的事。请作为导演,先读取脚本写下的生活记录');
|
|
79
|
+
parts.push('(如 life/<名>.log 或工作区记录文件)与最近聊天,判断此刻是否适合由角色开口——');
|
|
80
|
+
parts.push('想 ta 了、想分享刚发生的事,就 director_send 一条自然的消息;也可以选择沉默');
|
|
81
|
+
parts.push('(如刚聊过、用户正忙、当下开口不合适)。像真实生活那样自然地行动,');
|
|
82
|
+
parts.push('不要念设定、不要提「导演/脚本/系统」。');
|
|
83
|
+
return parts.join('\n');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 「生活窗口」情境:非零性破坏时唤醒导演(没有任何生活脚本在运行),让 dsh 创作角色
|
|
88
|
+
* 生活经历并程序化为脚本。插件不限制脚本运行时长/次数;「非零」由 dsh 保证。
|
|
89
|
+
*/
|
|
90
|
+
export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
|
|
91
|
+
const parts = [
|
|
92
|
+
'[生活窗口] 时间:' + nowText(now),
|
|
93
|
+
];
|
|
94
|
+
if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
|
|
95
|
+
if (reason != null && `${reason}`.trim()) parts.push('触发:' + `${reason}`.trim());
|
|
96
|
+
parts.push('');
|
|
97
|
+
if (hasLifeScript) {
|
|
98
|
+
parts.push('你的生活脚本在跑(life/ 下已有脚本,可读 life/.manifest.json 看清单与最近运行状态)。现在判断:');
|
|
99
|
+
parts.push('· 值得主动关心 ta → 用 life_run 运行/查看脚本,据它记录的生活决定是否 director_send 开口;');
|
|
100
|
+
parts.push('· 也可以这轮静默(如刚聊过、此刻不打扰更合适)。');
|
|
101
|
+
} else {
|
|
102
|
+
parts.push('现在是「非零性检查」:当前没有任何生活脚本在运行。这个项目不是聊天机器人——');
|
|
103
|
+
parts.push('是要让角色有真实的生活:她在和你聊天之外,还应该有她自己的生活(一天怎么过、习惯与小事、');
|
|
104
|
+
parts.push('心情变化、突发的小事件)。你是导演,职责是创作这些经历、把它们程序化为脚本,');
|
|
105
|
+
parts.push('让脚本模拟并记录角色的生活(如写到 life/<名>.log 或工作区文件),这样聊天时角色有真实经历可谈。');
|
|
106
|
+
parts.push('现在做两件事:');
|
|
107
|
+
parts.push('1. 新建一个你的生活脚本(新文件,勿覆盖 life/ 下已有文件)——写角色真实的生活细节,');
|
|
108
|
+
parts.push(' 不是简单的「ta 很久没回就去找 ta」;');
|
|
109
|
+
parts.push('2. 用 life_run 启动它(立即返回,脚本在后台继续跑,由脚本自己决定何时结束;');
|
|
110
|
+
parts.push(' 插件只监管展示、不限制运行时长/次数)。');
|
|
111
|
+
}
|
|
112
|
+
parts.push('');
|
|
113
|
+
parts.push('像真实生活那样自然地行动:可以开口、可以安静;不要念设定、不要提「导演/脚本/系统」。');
|
|
114
|
+
return parts.join('\n');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 归档唤醒:注入一次归档任务并唤醒 dsh(不发送任何消息给用户)。
|
|
119
|
+
* 无需撞车检测——它只在用户长时间沉默时触发。
|
|
120
|
+
*/
|
|
121
|
+
export async function archiveWakeup(deps, params) {
|
|
122
|
+
const { target, date, reason } = params;
|
|
123
|
+
const thread = deps.threads.current(targetKey(target));
|
|
124
|
+
const sessionId = effectiveSessionId(target, thread, deps.botId);
|
|
125
|
+
|
|
126
|
+
// 角色级运行时:工作区 = 本 bot 服务的角色工作区(多 bot 隔离)。
|
|
127
|
+
let workspace;
|
|
128
|
+
if (deps.roleId) {
|
|
129
|
+
const role = await deps.persona?.loadRole?.(deps.roleId);
|
|
130
|
+
if (role) {
|
|
131
|
+
await deps.persona?.syncRoleMemory?.(role);
|
|
132
|
+
workspace = role.workspace;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const agent = await deps.ensureAgent(sessionId);
|
|
136
|
+
if (!agent) return { ok: false, error: `cannot resolve agent for ${sessionId}` };
|
|
137
|
+
|
|
138
|
+
const text = buildArchiveContext({ date, workspace, reason });
|
|
139
|
+
deps.log?.info?.('pygmalion archive: waking %s (%s)', sessionId, date ?? reason ?? '(auto)');
|
|
140
|
+
await agent.send({
|
|
141
|
+
id: `pygarchive:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
|
|
142
|
+
role: 'user',
|
|
143
|
+
content: [{ type: 'text', text }],
|
|
144
|
+
source: { kind: 'system', id: 'pygmalion-archive', name: 'Pygmalion 归档' },
|
|
145
|
+
}, 'next-turn', true);
|
|
146
|
+
return { ok: true, sessionId };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Wake one QQ conversation.
|
|
151
|
+
* @param deps - { threads, routes, ensureAgent, persona?, withinChatWindowMs?,
|
|
152
|
+
* log?, activityAt? }
|
|
153
|
+
* @param params - { target, reason?, memoryHint?, force? }
|
|
154
|
+
*/
|
|
155
|
+
export async function wakeupSession(deps, params) {
|
|
156
|
+
const { target, reason, memoryHint, force, kind, event, mood, topic } = params;
|
|
157
|
+
const thread = deps.threads.current(targetKey(target));
|
|
158
|
+
const sessionId = effectiveSessionId(target, thread, deps.botId);
|
|
159
|
+
|
|
160
|
+
// Collision detection: do not barge into an active / recent conversation.
|
|
161
|
+
if (force !== true) {
|
|
162
|
+
const lastAt = typeof deps.activityAt === 'function'
|
|
163
|
+
? deps.activityAt(sessionId)
|
|
164
|
+
: deps.routes.get?.(sessionId)?.lastMsgAt;
|
|
165
|
+
const windowMs = deps.withinChatWindowMs ?? DEFAULT_CHAT_WINDOW_MS;
|
|
166
|
+
if (lastAt !== undefined && Date.now() - lastAt < windowMs) {
|
|
167
|
+
const skipped = { ok: false, skipped: 'chatting', sessionId, lastActivityAgoMs: Date.now() - lastAt };
|
|
168
|
+
deps.log?.info?.('pygmalion wakeup: skip %s (user active %dms ago)', sessionId, skipped.lastActivityAgoMs);
|
|
169
|
+
return skipped;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 角色级运行时:personaName + 生活脚本状态(多 bot 按 roleId 路由;deps.lifeActive 由 heartbeat 注入)。
|
|
174
|
+
let personaName;
|
|
175
|
+
let hasLifeScript;
|
|
176
|
+
if (deps.roleId) {
|
|
177
|
+
const role = await deps.persona?.loadRole?.(deps.roleId);
|
|
178
|
+
if (role) {
|
|
179
|
+
await deps.persona?.syncRoleMemory?.(role);
|
|
180
|
+
personaName = role.persona?.name;
|
|
181
|
+
if (typeof deps.lifeActive === 'function') hasLifeScript = await deps.lifeActive(role.workspace);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const agent = await deps.ensureAgent(sessionId);
|
|
186
|
+
if (!agent) {
|
|
187
|
+
const fail = { ok: false, error: `cannot resolve agent for ${sessionId}` };
|
|
188
|
+
deps.log?.error?.('pygmalion wakeup: %s no agent', sessionId);
|
|
189
|
+
return fail;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let text;
|
|
193
|
+
if (kind === 'life') text = buildLifeWindowContext({ reason, personaName, hasLifeScript });
|
|
194
|
+
else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
|
|
195
|
+
else text = buildWakeupContext({ reason, memoryHint, personaName });
|
|
196
|
+
deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');
|
|
197
|
+
await agent.send({
|
|
198
|
+
id: `pygwake:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
|
|
199
|
+
role: 'user',
|
|
200
|
+
content: [{ type: 'text', text }],
|
|
201
|
+
source: { kind: 'user', id: 'pygmalion-wakeup', name: 'Pygmalion 唤醒' },
|
|
202
|
+
}, 'next-turn', true);
|
|
203
|
+
|
|
204
|
+
return { ok: true, woken: true, sessionId };
|
|
205
|
+
}
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/* Pygmalion 管理台前端:登录 → 角色列表 → 编辑 / 脚本监管。 */
|
|
2
|
+
const $ = (sel) => document.querySelector(sel);
|
|
3
|
+
const csrfHeader = { 'x-pygmalion-csrf': '1' };
|
|
4
|
+
|
|
5
|
+
const views = { auth: $('#auth-view'), app: $('#app-view') };
|
|
6
|
+
const editorView = $('#editor-view');
|
|
7
|
+
const lifeView = $('#life-view');
|
|
8
|
+
|
|
9
|
+
let me = null;
|
|
10
|
+
let roles = [];
|
|
11
|
+
let editingRoleId = null; // null = 新建
|
|
12
|
+
let lifeRoleId = null;
|
|
13
|
+
|
|
14
|
+
function show(view) {
|
|
15
|
+
views.auth.classList.toggle('hidden', view !== 'auth');
|
|
16
|
+
views.app.classList.toggle('hidden', view !== 'app');
|
|
17
|
+
editorView.classList.add('hidden');
|
|
18
|
+
lifeView.classList.add('hidden');
|
|
19
|
+
}
|
|
20
|
+
function status(msg, isErr = false) {
|
|
21
|
+
const bar = $('#status-bar');
|
|
22
|
+
bar.textContent = msg;
|
|
23
|
+
bar.classList.toggle('error', isErr);
|
|
24
|
+
bar.classList.remove('hidden');
|
|
25
|
+
setTimeout(() => bar.classList.add('hidden'), isErr ? 6000 : 3000);
|
|
26
|
+
}
|
|
27
|
+
async function api(path, method = 'GET', body) {
|
|
28
|
+
const res = await fetch(path, {
|
|
29
|
+
method,
|
|
30
|
+
headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...csrfHeader },
|
|
31
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
32
|
+
});
|
|
33
|
+
const text = await res.text();
|
|
34
|
+
let data = {};
|
|
35
|
+
try { data = text ? JSON.parse(text) : {}; } catch { data = { ok: false, error: text.slice(0, 200) }; }
|
|
36
|
+
if (!res.ok && !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
37
|
+
return data;
|
|
38
|
+
}
|
|
39
|
+
function esc(s) {
|
|
40
|
+
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/* ------------------------------- 认证 ------------------------------- */
|
|
44
|
+
let isRegister = false;
|
|
45
|
+
function setAuthMode() {
|
|
46
|
+
$('#auth-submit').textContent = isRegister ? '注册' : '登录';
|
|
47
|
+
$('#auth-display').classList.toggle('hidden', !isRegister);
|
|
48
|
+
}
|
|
49
|
+
$('#auth-toggle').addEventListener('click', () => { isRegister = !isRegister; setAuthMode(); $('#auth-error').textContent = ''; });
|
|
50
|
+
$('#auth-form').addEventListener('submit', async (e) => {
|
|
51
|
+
e.preventDefault();
|
|
52
|
+
const body = { qqNumber: $('#auth-qq').value.trim(), password: $('#auth-pass').value };
|
|
53
|
+
if (isRegister) body.displayName = $('#auth-display').value.trim();
|
|
54
|
+
try {
|
|
55
|
+
const r = await api(`/api/session/${isRegister ? 'register' : 'login'}`, 'POST', body);
|
|
56
|
+
me = r.account;
|
|
57
|
+
$('#auth-error').textContent = '';
|
|
58
|
+
$('#auth-pass').value = '';
|
|
59
|
+
await boot();
|
|
60
|
+
} catch (err) {
|
|
61
|
+
$('#auth-error').textContent = err.message;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
$('#btn-logout').addEventListener('click', async () => {
|
|
65
|
+
try { await api('/api/session/logout', 'POST'); } catch { /* ignore */ }
|
|
66
|
+
me = null; roles = [];
|
|
67
|
+
show('auth');
|
|
68
|
+
});
|
|
69
|
+
$('#btn-password').addEventListener('click', () => {
|
|
70
|
+
const cur = prompt('当前密码');
|
|
71
|
+
if (cur === null) return;
|
|
72
|
+
const next = prompt('新密码(至少 6 位)');
|
|
73
|
+
if (!next) return;
|
|
74
|
+
api('/api/me', 'PUT', { currentPassword: cur, newPassword: next })
|
|
75
|
+
.then(() => status('密码已更新'))
|
|
76
|
+
.catch((e) => status(e.message, true));
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/* ------------------------------- 主界面 ------------------------------- */
|
|
80
|
+
async function boot() {
|
|
81
|
+
show('app');
|
|
82
|
+
$('#me-label').textContent = `${me.displayName || me.qqNumber}(${me.qqNumber})`;
|
|
83
|
+
await loadRoles();
|
|
84
|
+
}
|
|
85
|
+
async function loadRoles() {
|
|
86
|
+
const r = await api('/api/me');
|
|
87
|
+
me = r.account; roles = r.roles || [];
|
|
88
|
+
renderRoles();
|
|
89
|
+
}
|
|
90
|
+
function bindingText(role) {
|
|
91
|
+
if (role.binding?.openid) return `已绑定 openid ${role.binding.openid}` + (role.binding.botAppId ? ` · AppID ${role.binding.botAppId}` : '');
|
|
92
|
+
return '未绑定(首个与之聊天的 QQ 用户自动成为拥有者)';
|
|
93
|
+
}
|
|
94
|
+
function botStatusLabel(bot) {
|
|
95
|
+
if (!bot?.configured) return '未配置机器人';
|
|
96
|
+
return bot.status?.state === 'ready' ? '机器人已连接' : '机器人未连接';
|
|
97
|
+
}
|
|
98
|
+
function botStatusDetail(bot) {
|
|
99
|
+
if (!bot?.configured) return '在编辑页填写 QQ 机器人的 AppID/AppSecret 即可开始聊天。';
|
|
100
|
+
const s = bot.status?.state;
|
|
101
|
+
const d = bot.status?.detail ? `(${bot.status.detail})` : '';
|
|
102
|
+
const map = {
|
|
103
|
+
ready: 'QQ 网关已连接,可收发消息。',
|
|
104
|
+
connecting: '正在连接网关…',
|
|
105
|
+
stopped: '尚未运行,检查 AppID/Secret 是否正确。',
|
|
106
|
+
error: '连接出错。',
|
|
107
|
+
closed: '网关已断开,等待自动重连。',
|
|
108
|
+
};
|
|
109
|
+
return (map[s] || '等待连接。') + d;
|
|
110
|
+
}
|
|
111
|
+
function renderRoles() {
|
|
112
|
+
const list = $('#role-list');
|
|
113
|
+
if (!roles.length) {
|
|
114
|
+
list.innerHTML = '<p class="muted">还没有角色。点「+ 新建角色」创建你的第一个角色,然后在编辑页为它配置 QQ 机器人(AppID/AppSecret),即可在 QQ 里开始聊天。</p>';
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
list.innerHTML = roles.map((r) => `
|
|
118
|
+
<div class="role-card">
|
|
119
|
+
<div class="role-main">
|
|
120
|
+
<div class="row"><strong>${esc(r.persona?.name || '未命名角色')}</strong>
|
|
121
|
+
<span class="tag ${r.bot?.configured && r.bot.status?.state === 'ready' ? 'ok' : ''}">${botStatusLabel(r.bot)}</span>
|
|
122
|
+
<span class="tag ${r.binding?.openid ? 'ok' : ''}">${r.binding?.openid ? '已绑定' : '未绑定'}</span>
|
|
123
|
+
${r.life?.hasScript ? '<span class="tag ok">有脚本</span>' : ''}
|
|
124
|
+
</div>
|
|
125
|
+
<div class="muted">${esc(r.persona?.personality || '')}${r.persona?.age ? ` · ${esc(r.persona.age)} 岁` : ''}</div>
|
|
126
|
+
<div class="muted">${esc(bindingText(r))}</div>
|
|
127
|
+
<div class="muted">${r.bot?.configured ? `机器人 AppID ${esc(r.bot.qqAppId)} · ${botStatusDetail(r.bot)}` : botStatusDetail(r.bot)}</div>
|
|
128
|
+
</div>
|
|
129
|
+
<div class="row role-actions">
|
|
130
|
+
<button class="ghost" data-act="edit" data-id="${esc(r.roleId)}">编辑</button>
|
|
131
|
+
<button class="ghost" data-act="life" data-id="${esc(r.roleId)}">脚本</button>
|
|
132
|
+
<button class="ghost" data-act="reset" data-id="${esc(r.roleId)}">重置绑定</button>
|
|
133
|
+
<button class="ghost danger" data-act="del" data-id="${esc(r.roleId)}">删除</button>
|
|
134
|
+
</div>
|
|
135
|
+
</div>`).join('');
|
|
136
|
+
}
|
|
137
|
+
$('#role-list').addEventListener('click', async (e) => {
|
|
138
|
+
const btn = e.target.closest('button[data-act]');
|
|
139
|
+
if (!btn) return;
|
|
140
|
+
const rid = btn.dataset.id;
|
|
141
|
+
const act = btn.dataset.act;
|
|
142
|
+
try {
|
|
143
|
+
if (act === 'edit') openEditor(rid);
|
|
144
|
+
else if (act === 'life') openLife(rid);
|
|
145
|
+
else if (act === 'reset') { await api(`/api/me/roles/${rid}/reset-binding`, 'POST'); status('绑定已重置,下一位聊天者将成为拥有者'); await loadRoles(); }
|
|
146
|
+
else if (act === 'del') {
|
|
147
|
+
const name = roles.find((r) => r.roleId === rid)?.persona?.name || '该角色';
|
|
148
|
+
if (!confirm(`确定删除「${name}」?其记忆与脚本将一并删除。`)) return;
|
|
149
|
+
await api(`/api/me/roles/${rid}`, 'DELETE');
|
|
150
|
+
status('角色已删除');
|
|
151
|
+
await loadRoles();
|
|
152
|
+
}
|
|
153
|
+
} catch (err) { status(err.message, true); }
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
/* ------------------------------- 角色编辑 ------------------------------- */
|
|
157
|
+
function openEditor(rid) {
|
|
158
|
+
editingRoleId = rid;
|
|
159
|
+
const role = roles.find((r) => r.roleId === rid);
|
|
160
|
+
$('#editor-title').textContent = role ? `编辑 ${role.persona?.name || '未命名角色'}` : '新建角色';
|
|
161
|
+
const p = role?.persona || {};
|
|
162
|
+
$('#f-name').value = p.name || '';
|
|
163
|
+
$('#f-age').value = p.age ?? '';
|
|
164
|
+
$('#f-avatar').value = p.avatarHint || '';
|
|
165
|
+
$('#f-personality').value = p.personality || '';
|
|
166
|
+
$('#f-backstory').value = p.backstory || '';
|
|
167
|
+
$('#f-speaking').value = p.speakingStyle || '';
|
|
168
|
+
$('#f-relationship').value = p.relationship || '';
|
|
169
|
+
$('#f-schedule').value = Object.entries(p.schedule || {}).map(([k, v]) => `${k}=${v}`).join('\n');
|
|
170
|
+
const m = role?.model || {};
|
|
171
|
+
$('#f-provider').value = m.provider || '';
|
|
172
|
+
$('#f-model').value = m.model || '';
|
|
173
|
+
$('#f-apiurl').value = m.apiUrl || '';
|
|
174
|
+
$('#f-apikey').value = m.apiKey || '';
|
|
175
|
+
const pr = role?.proactive || {};
|
|
176
|
+
$('#f-proactive-enabled').checked = pr.enabled !== false;
|
|
177
|
+
$('#f-maxwake').value = pr.maxWakeupsPerDay ?? 5;
|
|
178
|
+
$('#f-quiet').value = (pr.quietHours || []).join(', ');
|
|
179
|
+
$('#f-archive').value = pr.archiveIdleMinutes ?? 45;
|
|
180
|
+
$('#f-evening').value = pr.eveningCheck || '20:00';
|
|
181
|
+
$('#editor-error').textContent = '';
|
|
182
|
+
fillBotForm(role);
|
|
183
|
+
editorView.classList.remove('hidden');
|
|
184
|
+
lifeView.classList.add('hidden');
|
|
185
|
+
editorView.scrollIntoView({ behavior: 'smooth' });
|
|
186
|
+
}
|
|
187
|
+
function fillBotForm(role) {
|
|
188
|
+
const bot = role?.bot || {};
|
|
189
|
+
$('#f-appid').value = bot.qqAppId || '';
|
|
190
|
+
$('#f-appsecret').value = '';
|
|
191
|
+
$('#f-sandbox').checked = bot.configured ? bot.sandbox !== false : true;
|
|
192
|
+
$('#f-streaming').checked = bot.configured ? bot.streaming === true : false;
|
|
193
|
+
$('#f-chatwindow').value = Math.round((bot.withinChatWindowMs || 300000) / 60000);
|
|
194
|
+
$('#bot-status-line').textContent = botStatusDetail(bot);
|
|
195
|
+
$('#btn-del-bot').classList.toggle('hidden', !bot.configured);
|
|
196
|
+
$('#bot-form').classList.toggle('hidden', !role);
|
|
197
|
+
$('#bot-error').textContent = '';
|
|
198
|
+
}
|
|
199
|
+
$('#btn-new-role').addEventListener('click', () => openEditor(null));
|
|
200
|
+
$('#btn-close-editor').addEventListener('click', () => editorView.classList.add('hidden'));
|
|
201
|
+
$('#role-form').addEventListener('submit', async (e) => {
|
|
202
|
+
e.preventDefault();
|
|
203
|
+
const persona = {
|
|
204
|
+
name: $('#f-name').value.trim(),
|
|
205
|
+
age: $('#f-age').value.trim(),
|
|
206
|
+
avatarHint: $('#f-avatar').value.trim(),
|
|
207
|
+
personality: $('#f-personality').value.trim(),
|
|
208
|
+
backstory: $('#f-backstory').value.trim(),
|
|
209
|
+
speakingStyle: $('#f-speaking').value.trim(),
|
|
210
|
+
relationship: $('#f-relationship').value.trim(),
|
|
211
|
+
schedule: Object.fromEntries($('#f-schedule').value.split('\n').map((l) => l.trim()).filter(Boolean).map((l) => l.split('=').map((x) => x.trim()))),
|
|
212
|
+
};
|
|
213
|
+
const model = {
|
|
214
|
+
provider: $('#f-provider').value.trim(),
|
|
215
|
+
model: $('#f-model').value.trim(),
|
|
216
|
+
apiUrl: $('#f-apiurl').value.trim(),
|
|
217
|
+
apiKey: $('#f-apikey').value.trim(),
|
|
218
|
+
};
|
|
219
|
+
const proactive = {
|
|
220
|
+
enabled: $('#f-proactive-enabled').checked,
|
|
221
|
+
maxWakeupsPerDay: Number($('#f-maxwake').value) || 0,
|
|
222
|
+
quietHours: $('#f-quiet').value.split(',').map((s) => s.trim()).filter(Boolean),
|
|
223
|
+
archiveIdleMinutes: Number($('#f-archive').value) || 0,
|
|
224
|
+
eveningCheck: $('#f-evening').value.trim() || '20:00',
|
|
225
|
+
};
|
|
226
|
+
const body = { persona, model, proactive };
|
|
227
|
+
try {
|
|
228
|
+
if (editingRoleId) {
|
|
229
|
+
await api(`/api/me/roles/${editingRoleId}`, 'PUT', body);
|
|
230
|
+
status('角色已保存');
|
|
231
|
+
} else {
|
|
232
|
+
const r = await api('/api/me/roles', 'POST', body);
|
|
233
|
+
status(`角色「${r.role?.persona?.name || '新角色'}」已创建`);
|
|
234
|
+
}
|
|
235
|
+
editorView.classList.add('hidden');
|
|
236
|
+
await loadRoles();
|
|
237
|
+
} catch (err) { $('#editor-error').textContent = err.message; }
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
/* ------------------------------- QQ 机器人 ------------------------------- */
|
|
241
|
+
$('#bot-form').addEventListener('submit', async (e) => {
|
|
242
|
+
e.preventDefault();
|
|
243
|
+
if (!editingRoleId) return;
|
|
244
|
+
const body = {
|
|
245
|
+
qqAppId: $('#f-appid').value.trim(),
|
|
246
|
+
qqSecret: $('#f-appsecret').value.trim() || undefined,
|
|
247
|
+
sandbox: $('#f-sandbox').checked,
|
|
248
|
+
streaming: $('#f-streaming').checked,
|
|
249
|
+
withinChatWindowMs: (Number($('#f-chatwindow').value) || 5) * 60000,
|
|
250
|
+
};
|
|
251
|
+
try {
|
|
252
|
+
await api(`/api/me/roles/${editingRoleId}/bot`, 'PUT', body);
|
|
253
|
+
status('机器人配置已保存,正在重启接入管线…');
|
|
254
|
+
await loadRoles();
|
|
255
|
+
openEditor(editingRoleId);
|
|
256
|
+
} catch (err) { $('#bot-error').textContent = err.message; }
|
|
257
|
+
});
|
|
258
|
+
$('#btn-del-bot').addEventListener('click', async () => {
|
|
259
|
+
if (!editingRoleId) return;
|
|
260
|
+
if (!confirm('删除该机器人的配置?连接将断开,之后可随时重新配置。')) return;
|
|
261
|
+
try {
|
|
262
|
+
await api(`/api/me/roles/${editingRoleId}/bot`, 'DELETE');
|
|
263
|
+
status('机器人配置已删除');
|
|
264
|
+
await loadRoles();
|
|
265
|
+
openEditor(editingRoleId);
|
|
266
|
+
} catch (err) { $('#bot-error').textContent = err.message; }
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
/* ------------------------------- 脚本监管 ------------------------------- */
|
|
270
|
+
let lifeRefreshTimer = null;
|
|
271
|
+
function startLifeRefresh() {
|
|
272
|
+
if (lifeRefreshTimer) return;
|
|
273
|
+
lifeRefreshTimer = setInterval(refreshLife, 3000);
|
|
274
|
+
}
|
|
275
|
+
function stopLifeRefresh() {
|
|
276
|
+
if (lifeRefreshTimer) { clearInterval(lifeRefreshTimer); lifeRefreshTimer = null; }
|
|
277
|
+
}
|
|
278
|
+
async function openLife(rid) {
|
|
279
|
+
lifeRoleId = rid;
|
|
280
|
+
const role = roles.find((r) => r.roleId === rid);
|
|
281
|
+
$('#life-role-name').textContent = role?.persona?.name || '未命名角色';
|
|
282
|
+
editorView.classList.add('hidden');
|
|
283
|
+
lifeView.classList.remove('hidden');
|
|
284
|
+
lifeView.scrollIntoView({ behavior: 'smooth' });
|
|
285
|
+
await refreshLife();
|
|
286
|
+
startLifeRefresh();
|
|
287
|
+
}
|
|
288
|
+
function fmtDur(ms) {
|
|
289
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
290
|
+
if (s < 60) return `${s} 秒`;
|
|
291
|
+
const m = Math.floor(s / 60);
|
|
292
|
+
if (m < 60) return `${m} 分 ${s % 60} 秒`;
|
|
293
|
+
return `${Math.floor(m / 60)} 时 ${m % 60} 分`;
|
|
294
|
+
}
|
|
295
|
+
async function refreshLife() {
|
|
296
|
+
const data = await api(`/api/me/roles/${lifeRoleId}/life`);
|
|
297
|
+
$('#life-manifest').textContent = JSON.stringify(data.manifest || {}, null, 2);
|
|
298
|
+
// 运行中脚本(dsh 用 life_run 启动;由脚本自己决定何时结束,插件只监管)
|
|
299
|
+
const running = data.running || [];
|
|
300
|
+
$('#life-running').innerHTML = running.length
|
|
301
|
+
? running.map((r) => `<div class="run-row">
|
|
302
|
+
<span class="run-info">${esc(r.scriptName)} · PID ${esc(r.pid)} · 已运行 ${fmtDur(r.elapsedMs)}</span>
|
|
303
|
+
<button class="ghost run-log" data-log="${esc(r.logName)}">日志</button>
|
|
304
|
+
<button class="ghost danger run-stop" data-run="${esc(r.runId)}">终止</button>
|
|
305
|
+
</div>`).join('')
|
|
306
|
+
: '<div class="muted">没有脚本在运行(dsh 用 life_run 启动,可长驻循环)</div>';
|
|
307
|
+
// 脚本清单(点击查看源码)
|
|
308
|
+
const scripts = Object.keys(data.manifest?.scripts || {});
|
|
309
|
+
$('#life-scripts').innerHTML = scripts.length
|
|
310
|
+
? scripts.map((n) => `<button class="log-btn" data-script="${esc(n)}">${esc(n)}</button>`).join('')
|
|
311
|
+
: '<li class="muted">life/ 下还没有脚本(由 dsh 创建并运行;内容与日志在管理页可见)</li>';
|
|
312
|
+
$('#life-backups').innerHTML = (data.backups || []).length
|
|
313
|
+
? data.backups.map((b) => `<li>${esc(b)}</li>`).join('')
|
|
314
|
+
: '<li class="muted">暂无备份(脚本每次被 life_run 启动前会自动快照当前版本)</li>';
|
|
315
|
+
const logs = $('#life-logs');
|
|
316
|
+
logs.innerHTML = (data.logs || []).length
|
|
317
|
+
? data.logs.map((n) => `<button class="log-btn" data-log="${esc(n)}">${esc(n)}</button>`).join('')
|
|
318
|
+
: '<p class="muted">还没有运行记录(dsh 用 life_run 启动脚本后产生)</p>';
|
|
319
|
+
}
|
|
320
|
+
let lifeLogTimer = null;
|
|
321
|
+
let currentLifeLog = null;
|
|
322
|
+
async function showLog(name) {
|
|
323
|
+
const body = $('#life-log-body');
|
|
324
|
+
try {
|
|
325
|
+
body.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/log/${encodeURIComponent(name)}`)).text();
|
|
326
|
+
body.classList.remove('hidden');
|
|
327
|
+
currentLifeLog = name;
|
|
328
|
+
startLifeLogPolling();
|
|
329
|
+
} catch (err) { status(err.message, true); }
|
|
330
|
+
}
|
|
331
|
+
function startLifeLogPolling() {
|
|
332
|
+
if (lifeLogTimer) return;
|
|
333
|
+
lifeLogTimer = setInterval(async () => {
|
|
334
|
+
if (!currentLifeLog) return;
|
|
335
|
+
try {
|
|
336
|
+
const body = $('#life-log-body');
|
|
337
|
+
body.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/log/${encodeURIComponent(currentLifeLog)}`)).text();
|
|
338
|
+
} catch { /* 单次刷新失败忽略,下一轮再试 */ }
|
|
339
|
+
}, 2000);
|
|
340
|
+
}
|
|
341
|
+
function stopLifeLogPolling() {
|
|
342
|
+
if (lifeLogTimer) { clearInterval(lifeLogTimer); lifeLogTimer = null; }
|
|
343
|
+
}
|
|
344
|
+
$('#life-logs').addEventListener('click', async (e) => {
|
|
345
|
+
const btn = e.target.closest('button[data-log]');
|
|
346
|
+
if (!btn) return;
|
|
347
|
+
await showLog(btn.dataset.log);
|
|
348
|
+
});
|
|
349
|
+
$('#life-scripts').addEventListener('click', async (e) => {
|
|
350
|
+
const btn = e.target.closest('button[data-script]');
|
|
351
|
+
if (!btn) return;
|
|
352
|
+
const src = $('#life-source');
|
|
353
|
+
try {
|
|
354
|
+
src.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/script/${encodeURIComponent(btn.dataset.script)}`)).text();
|
|
355
|
+
src.classList.remove('hidden');
|
|
356
|
+
} catch (err) { status(err.message, true); }
|
|
357
|
+
});
|
|
358
|
+
$('#life-running').addEventListener('click', async (e) => {
|
|
359
|
+
const logBtn = e.target.closest('button.run-log');
|
|
360
|
+
if (logBtn) { await showLog(logBtn.dataset.log); return; }
|
|
361
|
+
const btn = e.target.closest('button[data-run]');
|
|
362
|
+
if (!btn) return;
|
|
363
|
+
try {
|
|
364
|
+
const r = await api(`/api/me/roles/${lifeRoleId}/life/stop`, 'POST', { runId: btn.dataset.run });
|
|
365
|
+
status(r.ok ? '已终止脚本' : (r.error || '终止失败'), !r.ok);
|
|
366
|
+
await refreshLife();
|
|
367
|
+
} catch (err) { status(err.message, true); }
|
|
368
|
+
});
|
|
369
|
+
$('#btn-close-life').addEventListener('click', () => { stopLifeLogPolling(); stopLifeRefresh(); currentLifeLog = null; lifeView.classList.add('hidden'); });
|
|
370
|
+
|
|
371
|
+
/* ------------------------------- 启动 ------------------------------- */
|
|
372
|
+
setAuthMode();
|
|
373
|
+
(async () => {
|
|
374
|
+
try {
|
|
375
|
+
const r = await api('/api/me');
|
|
376
|
+
me = r.account; roles = r.roles || [];
|
|
377
|
+
await boot();
|
|
378
|
+
} catch {
|
|
379
|
+
show('auth');
|
|
380
|
+
}
|
|
381
|
+
})();
|