pygmalion 0.1.14 → 0.1.15
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 +1 -0
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/DEPLOY.md +1 -0
- package/docs/DEVICE.md +3 -3
- package/docs/PRESET.md +1 -1
- package/package.json +1 -1
- package/preset/pygmalion-director/agent.cordis.yml +36 -27
- package/src/bot-factory.js +9 -4
- package/src/devices/doc.mjs +2 -0
- package/src/devices/manager.mjs +62 -17
- package/src/heartbeat.js +6 -5
- package/src/message-review.js +276 -0
- package/src/persona.js +34 -18
- package/src/session-log.js +31 -2
- package/src/tools.js +133 -57
- package/src/voice-mimo.js +39 -9
- package/src/wakeup.js +33 -11
- package/src/web-public/app.js +15 -6
- package/src/web-public/index.html +2 -0
- package/src/web-server.js +14 -4
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* director_send 发送前审查。
|
|
3
|
+
*
|
|
4
|
+
* 两层边界:
|
|
5
|
+
* 1. 确定性校验只拒绝不可能属于角色消息的控制文本、系统标记、普通文字舞台标签、
|
|
6
|
+
* 空白项与同批重复;不按消息条数或逗号数量硬裁决。
|
|
7
|
+
* 2. 可选 LLM 审查独立判断 QQ 分句、近期复读、人物一致性与 reawake 时长是否自然。
|
|
8
|
+
* 审查器只给通过/退回意见,不代写角色消息。
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
const QQ_OPENID_RE = /^[0-9A-F]{32}$/i;
|
|
13
|
+
const SYSTEM_MARKER_RE = /\[(?:时间线|唤醒事件|脚本事件|生活窗口|脚本审阅|归档任务|设备事件|HTTP 推送记录)\]/;
|
|
14
|
+
const CONTROL_WORD_RE = /\b(?:reawake|director_send)\b/i;
|
|
15
|
+
const TEXT_STAGE_RE = /^\s*[((][^()()\r\n]{1,30}[))]/;
|
|
16
|
+
|
|
17
|
+
function textOfBlocks(content) {
|
|
18
|
+
return (Array.isArray(content) ? content : [])
|
|
19
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
20
|
+
.map((block) => block.text)
|
|
21
|
+
.join('')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function messageTexts(raw) {
|
|
26
|
+
const out = [];
|
|
27
|
+
for (const item of Array.isArray(raw) ? raw : []) {
|
|
28
|
+
const text = typeof item === 'string' ? item.trim() : String(item?.text ?? '').trim();
|
|
29
|
+
if (text) out.push(text);
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 把 director_send 的兼容输入规范化为内部消息对象。 */
|
|
35
|
+
export function normalizeDirectorMessages(raw) {
|
|
36
|
+
return (Array.isArray(raw) ? raw : []).map((item) => typeof item === 'string'
|
|
37
|
+
? { type: 'text', text: item.trim() }
|
|
38
|
+
: {
|
|
39
|
+
type: item?.type === 'voice' ? 'voice' : 'text',
|
|
40
|
+
text: String(item?.text ?? '').trim(),
|
|
41
|
+
scene: String(item?.scene ?? '').trim(),
|
|
42
|
+
direction: String(item?.direction ?? '').trim(),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function duplicateKey(text) {
|
|
47
|
+
return String(text).toLowerCase().replace(/\s+/g, '').replace(/[。!?!?…~~]+$/g, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 不依赖模型的硬校验。空 messages 合法(只安排 reawake);数组中的空白项不合法。
|
|
52
|
+
* 返回面向导演的具体退回理由。
|
|
53
|
+
*/
|
|
54
|
+
export function validateDirectorMessages(raw, messages = normalizeDirectorMessages(raw)) {
|
|
55
|
+
const issues = [];
|
|
56
|
+
const list = Array.isArray(raw) ? raw : [];
|
|
57
|
+
if (list.some((item) => (typeof item === 'string' ? item : item?.text) == null
|
|
58
|
+
|| String(typeof item === 'string' ? item : item?.text).trim().length === 0)) {
|
|
59
|
+
issues.push('messages 中含空白消息;空数组可以表示本次不发送,但数组中的每一项都必须有内容');
|
|
60
|
+
}
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
for (let i = 0; i < messages.length; i++) {
|
|
63
|
+
const msg = messages[i];
|
|
64
|
+
const label = `第 ${i + 1} 条消息`;
|
|
65
|
+
if (CONTROL_WORD_RE.test(msg.text)) issues.push(`${label}包含内部控制词`);
|
|
66
|
+
if (SYSTEM_MARKER_RE.test(msg.text)) issues.push(`${label}包含系统情境标记`);
|
|
67
|
+
if (msg.type === 'text' && TEXT_STAGE_RE.test(msg.text)) issues.push(`${label}以括号舞台/情绪标签开头;此类标签仅可用于语音台词`);
|
|
68
|
+
const key = duplicateKey(msg.text);
|
|
69
|
+
if (key && seen.has(key)) issues.push(`${label}与本次调用中的前一条消息重复`);
|
|
70
|
+
if (key) seen.add(key);
|
|
71
|
+
}
|
|
72
|
+
return [...new Set(issues)];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sentCountFromRendered(text) {
|
|
76
|
+
const success = String(text).match(/^已发送\s+(\d+)\s+条消息/);
|
|
77
|
+
const partial = String(text).match(/失败前已发送\s+(\d+)\s+条消息/);
|
|
78
|
+
return Number(success?.[1] ?? partial?.[1] ?? 0);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseDirectorCall(block, sentCounts) {
|
|
82
|
+
if (block?.type !== 'tool-call' || block.name !== 'director_send') return [];
|
|
83
|
+
// 新会话中的工具调用都有 id:只有配对结果明确显示至少发送一条时才进入真实 QQ 历史。
|
|
84
|
+
// 无 id 是旧日志/测试兼容形态,沿用原来的调用即发送假设。
|
|
85
|
+
const sentCount = block.id == null ? Number.MAX_SAFE_INTEGER : (sentCounts.get(String(block.id)) ?? 0);
|
|
86
|
+
if (sentCount < 1) return [];
|
|
87
|
+
try {
|
|
88
|
+
const args = JSON.parse(block.arguments ?? '{}');
|
|
89
|
+
return messageTexts(args.messages).slice(0, sentCount).map((text) => ({ role: 'character', text }));
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 从当前 agent 的派生消息中提取最近真实 QQ 对话。
|
|
97
|
+
* 工具执行时最后一条 assistant message 含本次候选 tool-call,必须排除,避免候选与自己比较。
|
|
98
|
+
*/
|
|
99
|
+
export function recentQQConversation(agent, limit = 30) {
|
|
100
|
+
let derived = [];
|
|
101
|
+
try { derived = agent?.session?.deriveMessages?.() ?? []; } catch { return []; }
|
|
102
|
+
const history = derived.length > 0 && derived.at(-1)?.role === 'assistant' ? derived.slice(0, -1) : derived;
|
|
103
|
+
const sentCounts = new Map();
|
|
104
|
+
for (const message of history) {
|
|
105
|
+
if (message?.role !== 'user') continue;
|
|
106
|
+
for (const block of Array.isArray(message.content) ? message.content : []) {
|
|
107
|
+
if (block?.type !== 'tool-result' || block.toolCallId == null) continue;
|
|
108
|
+
const rendered = textOfBlocks(block.content);
|
|
109
|
+
const count = sentCountFromRendered(rendered);
|
|
110
|
+
if (count > 0) sentCounts.set(String(block.toolCallId), count);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const out = [];
|
|
114
|
+
for (const message of history) {
|
|
115
|
+
if (message?.role === 'user' && message?.source?.kind === 'user'
|
|
116
|
+
&& typeof message.source.id === 'string' && QQ_OPENID_RE.test(message.source.id)) {
|
|
117
|
+
const text = textOfBlocks(message.content);
|
|
118
|
+
if (text) out.push({ role: 'user', text: text.slice(0, 1200) });
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (message?.role !== 'assistant') continue;
|
|
122
|
+
for (const block of Array.isArray(message.content) ? message.content : []) out.push(...parseDirectorCall(block, sentCounts));
|
|
123
|
+
}
|
|
124
|
+
return out.slice(-Math.max(1, limit));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 当前轮的模型侧情境(QQ 用户消息或唤醒注入),供审查器理解为什么会调用发送工具。 */
|
|
128
|
+
export function currentTurnContext(agent) {
|
|
129
|
+
let derived = [];
|
|
130
|
+
try { derived = agent?.session?.deriveMessages?.() ?? []; } catch { return ''; }
|
|
131
|
+
for (let i = derived.length - 1; i >= 0; i--) {
|
|
132
|
+
if (derived[i]?.role !== 'user') continue;
|
|
133
|
+
const text = textOfBlocks(derived[i].content);
|
|
134
|
+
if (text) return text.slice(0, 2400);
|
|
135
|
+
}
|
|
136
|
+
return '';
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 优先用审查覆盖配置,否则继承当前会话最后一次实际请求的 route,再退到 agent options。 */
|
|
140
|
+
export function resolveReviewRoute(reviewConfig, agent) {
|
|
141
|
+
const latest = agent?.session?.requestHeader?.()?.config;
|
|
142
|
+
const fallback = latest?.provider && latest?.model
|
|
143
|
+
? latest
|
|
144
|
+
: (agent?.options?.provider && agent?.options?.model ? agent.options : undefined);
|
|
145
|
+
const provider = String(reviewConfig?.provider ?? '').trim() || fallback?.provider;
|
|
146
|
+
const model = String(reviewConfig?.model ?? '').trim() || fallback?.model;
|
|
147
|
+
return provider && model ? { provider, model } : undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function personaForReview(role) {
|
|
151
|
+
const p = role?.persona ?? {};
|
|
152
|
+
return {
|
|
153
|
+
name: String(p.name ?? '').slice(0, 100),
|
|
154
|
+
age: String(p.age ?? '').slice(0, 100),
|
|
155
|
+
personality: String(p.personality ?? '').slice(0, 1200),
|
|
156
|
+
backstory: String(p.backstory ?? '').slice(0, 1600),
|
|
157
|
+
speakingStyle: String(p.speakingStyle ?? '').slice(0, 1200),
|
|
158
|
+
relationship: String(p.relationship ?? '').slice(0, 1200),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function buildReviewSystemPrompt() {
|
|
163
|
+
return [
|
|
164
|
+
'你是 Pygmalion 的 QQ 消息发送前审查器。你只判断候选输出是否自然,不扮演角色、不改写消息。',
|
|
165
|
+
'角色不是 AI agent、AI 助手或围绕用户任务运转的服务者。候选行动和发言必须由人物设定、过往经历、当前处境与关系状态共同支持,',
|
|
166
|
+
'不得呈现通用 AI 助手的默认目标、工作方式、话术结构或交互习惯。',
|
|
167
|
+
'人物设定中的说话风格说明、Q&A、示范对话和其他表达指导,是判断候选措辞、语气与表达方式的直接依据;明显偏离时应退回。',
|
|
168
|
+
'与明确人物设定冲突,或把导演、AI agent、AI 助手的特征带入角色的候选属于 OOC,必须退回。',
|
|
169
|
+
'近期聊天只用于判断事实、事件、承诺、关系变化和延续影响。不得把近期或更早的消息文本当作文风依据,也不得因历史中反复出现某种写法就认可它。',
|
|
170
|
+
'消息数量没有固定上限。闲聊回应常见一至两条;主动展开确有多个连续想法的话题时,三至五条或更多也可以。',
|
|
171
|
+
'每个气泡应是人在聊天框中自然敲出的一个语块。书面长句用逗号连接多个本可独立说出的分句通常不自然;',
|
|
172
|
+
'但不能为了增加数量机械拆句,也不能因条数多就判错。判断每个气泡是否有真实的分句、停顿、补充或推进理由。',
|
|
173
|
+
'重点识别:近期事实或问题复读;用户已经回答后仍追问;通用 AI 助手式表达;偏离人物设定中的语言指导;',
|
|
174
|
+
'照搬历史消息的表达习惯;为了展示人设而额外制造态度或语言特征;控制信息泄漏。',
|
|
175
|
+
'不预设角色对用户的态度方向,也不以亲密程度、配合程度或情绪性质本身作为通过或退回的依据。',
|
|
176
|
+
'reawake 必须让关系仍有继续的可能,但时长要符合现实:考虑用户离开手机、正在做的事、明确约定、',
|
|
177
|
+
'届时情境是否可能变化以及连续未回复后的自然等待。reason 是届时重新观察的线索,不能是预写好的下一条消息。',
|
|
178
|
+
'只输出一个 JSON 对象,不加 markdown 或解释:',
|
|
179
|
+
'{"messages":{"pass":true,"reasons":[]},"reawake":{"reasonable":true,"reason":""}}',
|
|
180
|
+
].join('\n');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function buildReviewInput({ role, agent, messages, reawake, reason }) {
|
|
184
|
+
return JSON.stringify({
|
|
185
|
+
persona: personaForReview(role),
|
|
186
|
+
currentContext: currentTurnContext(agent),
|
|
187
|
+
recentQQConversation: recentQQConversation(agent),
|
|
188
|
+
candidate: {
|
|
189
|
+
messages: messages.map((m) => ({ type: m.type, text: m.text })),
|
|
190
|
+
reawake: reawake ?? null,
|
|
191
|
+
reason: String(reason ?? '').slice(0, 1200),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function parseFirstObject(text) {
|
|
197
|
+
const start = text.indexOf('{');
|
|
198
|
+
if (start < 0) return undefined;
|
|
199
|
+
let depth = 0;
|
|
200
|
+
let quoted = false;
|
|
201
|
+
let escaped = false;
|
|
202
|
+
for (let i = start; i < text.length; i++) {
|
|
203
|
+
const ch = text[i];
|
|
204
|
+
if (quoted) {
|
|
205
|
+
if (escaped) escaped = false;
|
|
206
|
+
else if (ch === '\\') escaped = true;
|
|
207
|
+
else if (ch === '"') quoted = false;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (ch === '"') quoted = true;
|
|
211
|
+
else if (ch === '{') depth++;
|
|
212
|
+
else if (ch === '}' && --depth === 0) {
|
|
213
|
+
try { return JSON.parse(text.slice(start, i + 1)); } catch { return undefined; }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function normalizeReviewResult(value) {
|
|
220
|
+
if (!value || typeof value !== 'object' || typeof value.messages?.pass !== 'boolean'
|
|
221
|
+
|| typeof value.reawake?.reasonable !== 'boolean') {
|
|
222
|
+
throw new Error('审查模型没有返回规定的 JSON 结构');
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
messages: {
|
|
226
|
+
pass: value.messages.pass,
|
|
227
|
+
reasons: Array.isArray(value.messages.reasons)
|
|
228
|
+
? value.messages.reasons.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()).slice(0, 6)
|
|
229
|
+
: [],
|
|
230
|
+
},
|
|
231
|
+
reawake: {
|
|
232
|
+
reasonable: value.reawake.reasonable,
|
|
233
|
+
reason: typeof value.reawake.reason === 'string' ? value.reawake.reason.trim() : '',
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 一次独立的、无工具 LLM 审查调用。调用失败由上层按 fail-open 处理。 */
|
|
239
|
+
export async function reviewDirectorSend({ llm, agent, role, messages, reawake, reason, timeoutMs = 30_000 }) {
|
|
240
|
+
if (!llm || typeof llm.stream !== 'function') throw new Error('LLM 服务不可用');
|
|
241
|
+
const config = role?.proactive?.messageReview ?? {};
|
|
242
|
+
const route = resolveReviewRoute(config, agent);
|
|
243
|
+
if (!route) throw new Error('无法解析当前会话的审查 Provider/模型');
|
|
244
|
+
const controller = new AbortController();
|
|
245
|
+
const timer = setTimeout(() => controller.abort(new Error('消息审查超时')), timeoutMs);
|
|
246
|
+
let output = '';
|
|
247
|
+
let finish;
|
|
248
|
+
try {
|
|
249
|
+
const input = buildReviewInput({ role, agent, messages, reawake, reason });
|
|
250
|
+
const options = {
|
|
251
|
+
provider: route.provider,
|
|
252
|
+
model: route.model,
|
|
253
|
+
system: buildReviewSystemPrompt(),
|
|
254
|
+
messages: [{
|
|
255
|
+
id: randomUUID(), role: 'user',
|
|
256
|
+
content: [{ type: 'text', text: input }],
|
|
257
|
+
source: { kind: 'plugin', plugin: 'pygmalion' },
|
|
258
|
+
}],
|
|
259
|
+
temperature: 0,
|
|
260
|
+
maxTokens: 500,
|
|
261
|
+
signal: controller.signal,
|
|
262
|
+
};
|
|
263
|
+
for await (const chunk of llm.stream(options)) {
|
|
264
|
+
if (chunk?.type === 'text-delta') output += chunk.text;
|
|
265
|
+
else if (chunk?.type === 'block-end' && chunk.block?.type === 'text' && !output) output += chunk.block.text;
|
|
266
|
+
else if (chunk?.type === 'finish') finish = chunk.reason;
|
|
267
|
+
}
|
|
268
|
+
} finally {
|
|
269
|
+
clearTimeout(timer);
|
|
270
|
+
}
|
|
271
|
+
if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? '消息审查失败');
|
|
272
|
+
if (finish?.kind === 'tool-calls' || finish?.kind === 'max-tokens') throw new Error(`消息审查异常结束:${finish.kind}`);
|
|
273
|
+
const parsed = parseFirstObject(output);
|
|
274
|
+
if (!parsed) throw new Error('无法解析审查模型返回的 JSON');
|
|
275
|
+
return { ...normalizeReviewResult(parsed), route };
|
|
276
|
+
}
|
package/src/persona.js
CHANGED
|
@@ -39,11 +39,12 @@ export function dataRoot() {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
export const DEFAULT_MODEL = { provider: '', model: 'deepseek-v4-flash', vision: false };
|
|
42
|
-
export const DEFAULT_PROACTIVE = {
|
|
43
|
-
enabled: true, quietHours: [], maxWakeupsPerDay: 5,
|
|
44
|
-
lifeEnabled: true, archiveIdleMinutes: 45, eveningCheck: '20:00',
|
|
45
|
-
|
|
46
|
-
}
|
|
42
|
+
export const DEFAULT_PROACTIVE = {
|
|
43
|
+
enabled: true, quietHours: [], maxWakeupsPerDay: 5,
|
|
44
|
+
lifeEnabled: true, archiveIdleMinutes: 45, eveningCheck: '20:00',
|
|
45
|
+
messageReview: { enabled: true, provider: '', model: '' },
|
|
46
|
+
memeCollection: { enabled: false, intervalDays: 7, vision: { provider: '', model: '', apiUrl: '', apiKey: '' } },
|
|
47
|
+
};
|
|
47
48
|
|
|
48
49
|
/**
|
|
49
50
|
* 从 dsh session id 提取 QQ 目标 id(c2c=openid / group=群 id / channel=频道 id)。
|
|
@@ -259,17 +260,27 @@ export function roleWorkspace(roleId) { return join(roleDir(roleId), 'workspace'
|
|
|
259
260
|
function roleJson(roleId, name, fallback) { return readJson(join(roleDir(roleId), name), fallback); }
|
|
260
261
|
|
|
261
262
|
/** 聚合加载一个角色的全部配置。persona.json 缺失 → null(目录非角色)。 */
|
|
262
|
-
export async function loadRole(roleId) {
|
|
263
|
+
export async function loadRole(roleId) {
|
|
263
264
|
if (!roleId) return null;
|
|
264
265
|
const dir = roleDir(roleId);
|
|
265
266
|
if (!existsSync(join(dir, 'persona.json'))) return null;
|
|
266
267
|
const persona = await roleJson(roleId, 'persona.json', null);
|
|
267
268
|
if (!persona) return null;
|
|
268
|
-
|
|
269
|
+
const savedProactive = await roleJson(roleId, 'proactive.json', {});
|
|
270
|
+
return {
|
|
269
271
|
roleId,
|
|
270
272
|
persona,
|
|
271
273
|
model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
|
|
272
|
-
proactive: {
|
|
274
|
+
proactive: {
|
|
275
|
+
...DEFAULT_PROACTIVE,
|
|
276
|
+
...savedProactive,
|
|
277
|
+
messageReview: { ...DEFAULT_PROACTIVE.messageReview, ...(savedProactive.messageReview ?? {}) },
|
|
278
|
+
memeCollection: {
|
|
279
|
+
...DEFAULT_PROACTIVE.memeCollection,
|
|
280
|
+
...(savedProactive.memeCollection ?? {}),
|
|
281
|
+
vision: { ...DEFAULT_PROACTIVE.memeCollection.vision, ...(savedProactive.memeCollection?.vision ?? {}) },
|
|
282
|
+
},
|
|
283
|
+
},
|
|
273
284
|
binding: await roleJson(roleId, 'binding.json', {}),
|
|
274
285
|
state: await roleJson(roleId, 'state.json', {}),
|
|
275
286
|
voice: await roleJson(roleId, 'voice/mimo.json', {}),
|
|
@@ -389,22 +400,27 @@ export async function isRoleDirectorSession(roleId, sessionId) {
|
|
|
389
400
|
return role ? role.binding.openid === openid && Boolean(role.persona) : false;
|
|
390
401
|
}
|
|
391
402
|
|
|
392
|
-
/**
|
|
393
|
-
|
|
403
|
+
/**
|
|
404
|
+
* 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。
|
|
405
|
+
* replaceId 只用于替换一次被发送审查退回时保留下来的兜底安排;普通调用仍可并存多个等待。
|
|
406
|
+
*/
|
|
407
|
+
export async function scheduleRewake(roleId, minutes, reason, { replaceId } = {}) {
|
|
394
408
|
const role = await loadRole(roleId);
|
|
395
409
|
if (!role) return { ok: false, atMs: 0, error: '角色不存在' };
|
|
396
410
|
const minutesN = Math.min(Math.max(Number(minutes) || 5, 1), 1440);
|
|
397
|
-
const atMs = Date.now() + minutesN * 60_000;
|
|
398
|
-
const createdAt = Date.now();
|
|
411
|
+
const atMs = Date.now() + minutesN * 60_000;
|
|
412
|
+
const createdAt = Date.now();
|
|
413
|
+
const id = randomBytes(8).toString('hex');
|
|
399
414
|
// 只保留「尚未到期」的等待;最多保留 MAX_PENDING-1 条旧待唤醒 + 本次,
|
|
400
415
|
// 防止堆积大量未来唤醒来回重复唤醒。(旧记录若曾触发过会在 heartbeat 侧被移除)
|
|
401
416
|
const MAX_PENDING = 5;
|
|
402
|
-
const state = { ...role.state, rewake: role.state.rewake ?? [] };
|
|
403
|
-
const pending = (Array.isArray(state.rewake) ? state.rewake : [])
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
417
|
+
const state = { ...role.state, rewake: role.state.rewake ?? [] };
|
|
418
|
+
const pending = (Array.isArray(state.rewake) ? state.rewake : [])
|
|
419
|
+
.filter((r) => r.atMs > createdAt && (replaceId === undefined || r.id !== replaceId));
|
|
420
|
+
state.rewake = [...pending.slice(-(MAX_PENDING - 1)), { id, atMs, reason: String(reason ?? '').trim() || '到时重新观察当前情境', createdAt }];
|
|
421
|
+
await saveRoleField(roleId, 'state', state);
|
|
422
|
+
return { ok: true, atMs, id };
|
|
423
|
+
}
|
|
408
424
|
|
|
409
425
|
// ---------------------------------------------------------------- 记忆 --
|
|
410
426
|
/** 人设 → memory-root 的 markdown(导演开场读)。 */
|
package/src/session-log.js
CHANGED
|
@@ -114,6 +114,26 @@ export function isRealUserMessage(ev) {
|
|
|
114
114
|
export function extractMessages(events) {
|
|
115
115
|
const userSeen = new Set();
|
|
116
116
|
const msgs = [];
|
|
117
|
+
// 新版工具调用只有在配对 tool/result 明确确认至少发送一条时才算真实角色消息。
|
|
118
|
+
// 审查退回/硬拦截同样会留下 tool/call,不能把未送达的候选写进长期原文。
|
|
119
|
+
const sentDirectorCalls = new Map();
|
|
120
|
+
for (const ev of events) {
|
|
121
|
+
if (ev?.type !== 'tool/result') continue;
|
|
122
|
+
const callId = ev.data?.message?.source?.callId;
|
|
123
|
+
const blocks = ev.data?.message?.content;
|
|
124
|
+
const rendered = (Array.isArray(blocks) ? blocks : [])
|
|
125
|
+
.filter((b) => b?.type === 'tool-result')
|
|
126
|
+
.flatMap((b) => Array.isArray(b.content) ? b.content : [])
|
|
127
|
+
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
128
|
+
.map((b) => b.text).join('');
|
|
129
|
+
const success = rendered.match(/^已发送\s+(\d+)\s+条消息/);
|
|
130
|
+
const partial = rendered.match(/失败前已发送\s+(\d+)\s+条消息/);
|
|
131
|
+
const count = Number(success?.[1] ?? partial?.[1] ?? 0);
|
|
132
|
+
const timeoutMatch = rendered.match(/第\s+([\d、,,\s]+)\s+条语音合成超时/);
|
|
133
|
+
const voiceTimeouts = new Set((timeoutMatch?.[1] ?? '').split(/[、,,\s]+/)
|
|
134
|
+
.map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
|
135
|
+
if (callId != null && count > 0) sentDirectorCalls.set(String(callId), { count, voiceTimeouts });
|
|
136
|
+
}
|
|
117
137
|
const push = (role, time, text) => {
|
|
118
138
|
const clean = cleanUserText(text);
|
|
119
139
|
if (!clean || isSystemText(clean)) return;
|
|
@@ -129,11 +149,20 @@ export function extractMessages(events) {
|
|
|
129
149
|
userSeen.add(key);
|
|
130
150
|
push('user', ev.time, t);
|
|
131
151
|
} else if (ev?.type === 'tool/call' && ev.data?.name === 'director_send') {
|
|
152
|
+
// 旧记录可能没有 callId,继续兼容;有 callId 的新记录必须由 tool/result 证明已发送。
|
|
153
|
+
const delivery = ev.data.callId == null
|
|
154
|
+
? { count: Number.MAX_SAFE_INTEGER, voiceTimeouts: new Set() }
|
|
155
|
+
: sentDirectorCalls.get(String(ev.data.callId));
|
|
156
|
+
const sentCount = delivery?.count ?? 0;
|
|
157
|
+
if (sentCount < 1) continue;
|
|
132
158
|
try {
|
|
133
159
|
const args = JSON.parse(ev.data.arguments ?? '{}');
|
|
134
|
-
|
|
160
|
+
const delivered = (Array.isArray(args.messages) ? args.messages : []).slice(0, sentCount);
|
|
161
|
+
for (let index = 0; index < delivered.length; index++) {
|
|
162
|
+
const m = delivered[index];
|
|
135
163
|
if (typeof m === 'string') push('character', ev.time, m);
|
|
136
|
-
else if (m && typeof m.text === 'string') push('character', ev.time,
|
|
164
|
+
else if (m && typeof m.text === 'string') push('character', ev.time,
|
|
165
|
+
m.type === 'voice' && !delivery.voiceTimeouts.has(index + 1) ? `[语音] ${m.text}` : m.text);
|
|
137
166
|
}
|
|
138
167
|
} catch { /* skip malformed */ }
|
|
139
168
|
}
|