pygmalion 0.1.15 → 0.2.1
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/LICENSE +21 -0
- package/README.md +141 -70
- package/THIRD_PARTY.md +9 -0
- package/docs/ARCHITECTURE.md +66 -108
- package/docs/DEPLOY.md +33 -137
- package/docs/DEVELOPMENT.md +67 -0
- package/docs/DEVICE.md +56 -47
- package/docs/EXTENSIONS.md +176 -0
- package/docs/PRESET.md +21 -63
- package/docs/UPGRADE-0.2.md +52 -0
- package/package.json +52 -33
- package/preset/pygmalion-director/cordis.patch.yml +234 -0
- package/preset/pygmalion-director/pygmalion-tools.js +43 -41
- package/scripts/start-local-test.mjs +45 -45
- package/skills/pygmalion-life-scripts/SKILL.md +12 -0
- package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
- package/skills/pygmalion-memory-archive/SKILL.md +24 -0
- package/skills/pygmalion-toy-control/SKILL.md +16 -0
- package/src/agent-life.js +608 -606
- package/src/archive-tools.js +9 -0
- package/src/bot-factory.js +129 -311
- package/src/bots.js +264 -275
- package/src/channel-qq.js +262 -0
- package/src/config.js +69 -68
- package/src/delivery-receipt.js +36 -0
- package/src/delivery-scope.js +20 -0
- package/src/devices/manager.mjs +80 -570
- package/src/devices/monsterparty-controller.mjs +393 -0
- package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
- package/src/devices/monsterparty.mjs +294 -294
- package/src/devices/pb.mjs +110 -110
- package/src/devices/registry.mjs +19 -0
- package/src/devices/script-helper.mjs +45 -0
- package/src/devices/scripts.mjs +109 -0
- package/src/devices/service.mjs +254 -0
- package/src/director-messages.js +35 -0
- package/src/dsh-runtime.js +17 -0
- package/src/extension-config.js +20 -0
- package/src/extensions.js +118 -0
- package/src/heartbeat.js +118 -97
- package/src/http-api.js +519 -509
- package/src/inbound.js +36 -207
- package/src/index.js +109 -37
- package/src/llm-provider.js +214 -171
- package/src/meme-worker.js +35 -39
- package/src/memebox.js +1 -1
- package/src/memory-recall.js +55 -0
- package/src/memory-write.js +136 -133
- package/src/peer-identity.js +26 -0
- package/src/persona.js +132 -69
- package/src/role-agent.js +155 -0
- package/src/role-runtime.js +65 -0
- package/src/roleplay-config.js +37 -0
- package/src/roleplay-format.js +37 -0
- package/src/roleplay-generation.js +46 -0
- package/src/roleplay-materials.js +113 -0
- package/src/roleplay-output.js +19 -0
- package/src/roleplay-parallel.js +239 -0
- package/src/roleplay-session.js +134 -0
- package/src/roleplay-worker.js +10 -0
- package/src/session-log.js +180 -172
- package/src/setup-agent.js +92 -100
- package/src/skills.js +97 -0
- package/src/slash-commands.js +155 -142
- package/src/speech-input.js +20 -0
- package/src/threads.js +2 -1
- package/src/tools.js +226 -254
- package/src/voice-defaults.js +13 -0
- package/src/voice-mimo.js +139 -125
- package/src/voice.js +200 -0
- package/src/wakeup.js +85 -66
- package/src/web-public/app.js +542 -382
- package/src/web-public/index.html +161 -158
- package/src/web-public/layout.css +7 -7
- package/src/web-public/style.css +12 -8
- package/src/web-server.js +161 -102
- package/src/worker-tools.js +18 -0
- package/templates/sample-life.mjs +59 -59
- package/templates/sample-toy.mjs +33 -33
- package/preset/pygmalion-director/agent.cordis.yml +0 -262
- package/preset/pygmalion-director/preset.yml +0 -3
- package/src/message-review.js +0 -276
package/src/persona.js
CHANGED
|
@@ -24,7 +24,8 @@ import { fileURLToPath } from 'node:url';
|
|
|
24
24
|
import path from 'node:path';
|
|
25
25
|
import { homedir } from 'node:os';
|
|
26
26
|
import { scryptSync, randomBytes, timingSafeEqual, createHash } from 'node:crypto';
|
|
27
|
-
import {
|
|
27
|
+
import { normalizeRoleplayConfig } from './roleplay-config.js';
|
|
28
|
+
import { peerIdentity, samePeer } from './peer-identity.js';
|
|
28
29
|
|
|
29
30
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
30
31
|
|
|
@@ -39,12 +40,11 @@ export function dataRoot() {
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
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
|
-
|
|
47
|
-
};
|
|
43
|
+
export const DEFAULT_PROACTIVE = {
|
|
44
|
+
enabled: true, quietHours: [], maxWakeupsPerDay: 5,
|
|
45
|
+
lifeEnabled: true, archiveIdleMinutes: 45, eveningCheck: '20:00',
|
|
46
|
+
memeCollection: { enabled: false, intervalDays: 7, vision: { provider: '', model: '', apiUrl: '', apiKey: '' } },
|
|
47
|
+
};
|
|
48
48
|
|
|
49
49
|
/**
|
|
50
50
|
* 从 dsh session id 提取 QQ 目标 id(c2c=openid / group=群 id / channel=频道 id)。
|
|
@@ -55,6 +55,7 @@ export const DEFAULT_PROACTIVE = {
|
|
|
55
55
|
export function openidFromSessionId(sessionId) {
|
|
56
56
|
const stripped = String(sessionId ?? '').split('#')[0];
|
|
57
57
|
const parts = stripped.split(':');
|
|
58
|
+
if (parts[0] !== 'qq') return undefined;
|
|
58
59
|
// 新格式:qq:v2:<botId>:<scope>:<id>(parts[1]===v2,parts[3]===scope)
|
|
59
60
|
if (parts[1] === 'v2' && (parts[3] === 'c2c' || parts[3] === 'group' || parts[3] === 'channel') && parts[4] != null && parts[4].length > 0)
|
|
60
61
|
return parts[4];
|
|
@@ -185,11 +186,12 @@ export async function loadDevice(deviceId) {
|
|
|
185
186
|
if (!deviceId) return null;
|
|
186
187
|
return await readJson(devicePath(deviceId), null);
|
|
187
188
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
export async function saveDevice(device) { await atomicWriteJson(devicePath(device.id), device); }
|
|
190
|
+
/** 建设备并回写账号 deviceIds;驱动类型由调用方明确选择。 */
|
|
191
|
+
export async function createDevice({ owner, alias, kind, config = {} }) {
|
|
192
|
+
if (!owner || !String(alias ?? '').trim() || !/^[a-z][a-z0-9._-]*$/.test(kind ?? '')) return null;
|
|
191
193
|
const id = `dev-${randomBytes(8).toString('hex')}`;
|
|
192
|
-
const device = { id, owner, kind, alias: String(alias).trim(), createdAt: Date.now() };
|
|
194
|
+
const device = { id, owner, kind, config, alias: String(alias).trim(), createdAt: Date.now() };
|
|
193
195
|
await atomicWriteJson(devicePath(id), device);
|
|
194
196
|
const account = await loadAccount(owner);
|
|
195
197
|
if (account) {
|
|
@@ -223,7 +225,7 @@ export async function deleteDevice(deviceId) {
|
|
|
223
225
|
return { removed: true, roleIds };
|
|
224
226
|
}
|
|
225
227
|
/** 角色授权设备的文档(memory/设备.md 内容);无授权合法设备 → null。 */
|
|
226
|
-
export async function renderDeviceDoc(role) {
|
|
228
|
+
export async function renderDeviceDoc(role, render) {
|
|
227
229
|
const persona = role?.persona;
|
|
228
230
|
const ids = Array.isArray(persona?.devices) ? persona.devices : [];
|
|
229
231
|
if (!ids.length) return null;
|
|
@@ -232,7 +234,7 @@ export async function renderDeviceDoc(role) {
|
|
|
232
234
|
for (const id of ids) {
|
|
233
235
|
const dev = await loadDevice(id);
|
|
234
236
|
if (!dev || dev.owner !== owner) continue; // 只渲染存在且属于本账号的
|
|
235
|
-
parts.push(
|
|
237
|
+
parts.push(render ? await render(dev) : `# 设备:${dev.alias}\n\n标识:${dev.id}\n驱动:${dev.kind}\n使用前加载对应设备 skill;能力以驱动声明为准。`);
|
|
236
238
|
}
|
|
237
239
|
return parts.length ? parts.join('\n\n') : null;
|
|
238
240
|
}
|
|
@@ -260,30 +262,32 @@ export function roleWorkspace(roleId) { return join(roleDir(roleId), 'workspace'
|
|
|
260
262
|
function roleJson(roleId, name, fallback) { return readJson(join(roleDir(roleId), name), fallback); }
|
|
261
263
|
|
|
262
264
|
/** 聚合加载一个角色的全部配置。persona.json 缺失 → null(目录非角色)。 */
|
|
263
|
-
export async function loadRole(roleId) {
|
|
265
|
+
export async function loadRole(roleId) {
|
|
264
266
|
if (!roleId) return null;
|
|
265
267
|
const dir = roleDir(roleId);
|
|
266
268
|
if (!existsSync(join(dir, 'persona.json'))) return null;
|
|
267
269
|
const persona = await roleJson(roleId, 'persona.json', null);
|
|
268
270
|
if (!persona) return null;
|
|
269
|
-
const savedProactive = await roleJson(roleId, 'proactive.json', {});
|
|
270
|
-
|
|
271
|
+
const savedProactive = await roleJson(roleId, 'proactive.json', {});
|
|
272
|
+
// 兼容旧配置:已移除的发送审查字段不再进入运行时。
|
|
273
|
+
delete savedProactive.messageReview;
|
|
274
|
+
return {
|
|
271
275
|
roleId,
|
|
272
276
|
persona,
|
|
273
277
|
model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
...
|
|
277
|
-
|
|
278
|
-
memeCollection: {
|
|
279
|
-
...DEFAULT_PROACTIVE.memeCollection,
|
|
280
|
-
...(savedProactive.memeCollection ?? {}),
|
|
281
|
-
vision: { ...DEFAULT_PROACTIVE.memeCollection.vision, ...(savedProactive.memeCollection?.vision ?? {}) },
|
|
282
|
-
},
|
|
283
|
-
},
|
|
278
|
+
roleplay: normalizeRoleplayConfig(await roleJson(roleId, 'roleplay.json', {})),
|
|
279
|
+
proactive: {
|
|
280
|
+
...DEFAULT_PROACTIVE,
|
|
281
|
+
...savedProactive,
|
|
282
|
+
memeCollection: {
|
|
283
|
+
...DEFAULT_PROACTIVE.memeCollection,
|
|
284
|
+
...(savedProactive.memeCollection ?? {}),
|
|
285
|
+
vision: { ...DEFAULT_PROACTIVE.memeCollection.vision, ...(savedProactive.memeCollection?.vision ?? {}) },
|
|
286
|
+
},
|
|
287
|
+
},
|
|
284
288
|
binding: await roleJson(roleId, 'binding.json', {}),
|
|
285
|
-
state: await roleJson(roleId, 'state.json', {}),
|
|
286
|
-
voice: await roleJson(roleId, 'voice/mimo.json', {}),
|
|
289
|
+
state: await roleJson(roleId, 'state.json', {}),
|
|
290
|
+
voice: await roleJson(roleId, 'voice/mimo.json', {}),
|
|
287
291
|
workspace: roleWorkspace(roleId),
|
|
288
292
|
};
|
|
289
293
|
}
|
|
@@ -326,17 +330,50 @@ export async function createRole({ accountId, persona }) {
|
|
|
326
330
|
return roleId;
|
|
327
331
|
}
|
|
328
332
|
export async function deleteRole(roleId) {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
acc.roleIds
|
|
334
|
-
|
|
333
|
+
return serializeRole(roleId, async () => {
|
|
334
|
+
const { rm } = await import('node:fs/promises');
|
|
335
|
+
await rm(roleDir(roleId), { recursive: true, force: true });
|
|
336
|
+
for (const acc of await listAccounts()) {
|
|
337
|
+
if ((acc.roleIds || []).includes(roleId)) {
|
|
338
|
+
acc.roleIds = acc.roleIds.filter((r) => r !== roleId);
|
|
339
|
+
await saveAccount(acc);
|
|
340
|
+
}
|
|
335
341
|
}
|
|
336
|
-
}
|
|
342
|
+
});
|
|
337
343
|
}
|
|
338
344
|
|
|
339
345
|
// ---------------------------------------------------------------- 绑定 --
|
|
346
|
+
const roleQueues = new Map();
|
|
347
|
+
function serializeRole(roleId, action) {
|
|
348
|
+
const key = join(dataRoot(), 'roles', safeId(roleId));
|
|
349
|
+
const pending = (roleQueues.get(key) ?? Promise.resolve()).catch(() => {}).then(action);
|
|
350
|
+
roleQueues.set(key, pending);
|
|
351
|
+
return pending.finally(() => { if (roleQueues.get(key) === pending) roleQueues.delete(key); });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 规范化身份的首聊绑定;调用方只能为已确认的实时私人入站显式允许新绑定。 */
|
|
355
|
+
export async function bindRoleIdentity(roleId, value, { allowNewBinding = false } = {}) {
|
|
356
|
+
const identity = peerIdentity(value);
|
|
357
|
+
return serializeRole(roleId, async () => {
|
|
358
|
+
const role = await loadRole(roleId);
|
|
359
|
+
if (!role) return { status: 'no-role' };
|
|
360
|
+
const existing = role.binding.peer ?? (role.binding.openid && role.binding.botAppId
|
|
361
|
+
? { adapterId: 'qq-official', accountId: role.binding.botAppId, peerId: role.binding.openid } : undefined);
|
|
362
|
+
if (existing) return { status: samePeer(existing, identity) ? 'already' : 'mismatch', role };
|
|
363
|
+
// 无账号作用域的历史绑定不能由另一种接入猜测认领。
|
|
364
|
+
if (role.binding.openid) {
|
|
365
|
+
if (!allowNewBinding || identity.adapterId !== 'qq-official' || role.binding.openid !== identity.peerId) return { status: 'mismatch', role };
|
|
366
|
+
// 历史 QQ 记录缺 AppID 时,仅由当前角色的实时 QQ 入站补全作用域。
|
|
367
|
+
await saveRoleField(roleId, 'binding', { ...role.binding, peer: identity, botAppId: identity.accountId });
|
|
368
|
+
return { status: 'already', role: await loadRole(roleId) };
|
|
369
|
+
}
|
|
370
|
+
if (!allowNewBinding) return { status: 'not-eligible', role };
|
|
371
|
+
const binding = { ...role.binding, peer: identity, revision: (role.binding.revision ?? 0) + 1 };
|
|
372
|
+
if (identity.adapterId === 'qq-official') Object.assign(binding, { openid: identity.peerId, botAppId: identity.accountId });
|
|
373
|
+
await saveRoleField(roleId, 'binding', binding);
|
|
374
|
+
return { status: 'bound', role: await loadRole(roleId) };
|
|
375
|
+
});
|
|
376
|
+
}
|
|
340
377
|
/**
|
|
341
378
|
* openid 绑定到角色(修 D5):
|
|
342
379
|
* 未绑定 → 首聊自动绑定为拥有者(记录服务该角色的 bot AppID),返回 { status:'bound' }
|
|
@@ -344,22 +381,41 @@ export async function deleteRole(roleId) {
|
|
|
344
381
|
* 已绑定不同 openid → { status:'mismatch' }(拒绝,不覆盖)
|
|
345
382
|
*/
|
|
346
383
|
export async function bindRoleOpenid(roleId, openid, botAppId) {
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
384
|
+
if (botAppId && openid) return bindRoleIdentity(roleId,
|
|
385
|
+
{ adapterId: 'qq-official', accountId: String(botAppId), peerId: openid }, { allowNewBinding: true });
|
|
386
|
+
return serializeRole(roleId, async () => {
|
|
387
|
+
const role = await loadRole(roleId);
|
|
388
|
+
if (!role) return { status: 'no-role' };
|
|
389
|
+
if (!openid) return { status: 'no-openid' };
|
|
390
|
+
const existing = role.binding.openid;
|
|
391
|
+
if (role.binding.peer && role.binding.peer.adapterId !== 'qq-official') return { status: 'mismatch', role };
|
|
392
|
+
if (existing) return existing === openid ? { status: 'already', role } : { status: 'mismatch', role };
|
|
393
|
+
role.binding.openid = openid;
|
|
394
|
+
role.binding.revision = (role.binding.revision ?? 0) + 1;
|
|
395
|
+
if (botAppId) role.binding.botAppId = String(botAppId);
|
|
396
|
+
await saveRoleField(roleId, 'binding', role.binding);
|
|
397
|
+
return { status: 'bound', role: await loadRole(roleId) };
|
|
398
|
+
});
|
|
356
399
|
}
|
|
357
400
|
/** 重置绑定(管理网页"支持重置绑定")。 */
|
|
358
401
|
export async function resetRoleBinding(roleId) {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
402
|
+
return serializeRole(roleId, async () => {
|
|
403
|
+
const role = await loadRole(roleId);
|
|
404
|
+
if (!role) return null;
|
|
405
|
+
await saveRoleField(roleId, 'binding', { ...role.binding, peer: undefined, openid: undefined, revision: (role.binding.revision ?? 0) + 1 });
|
|
406
|
+
return await loadRole(roleId);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 角色状态的读改写使用同一角色队列,避免后台任务覆盖新等待或删除后重建目录。 */
|
|
411
|
+
export async function updateRoleState(roleId, update) {
|
|
412
|
+
return serializeRole(roleId, async () => {
|
|
413
|
+
const role = await loadRole(roleId);
|
|
414
|
+
if (!role) return null;
|
|
415
|
+
const state = await update({ ...role.state });
|
|
416
|
+
await saveRoleField(roleId, 'state', state);
|
|
417
|
+
return state;
|
|
418
|
+
});
|
|
363
419
|
}
|
|
364
420
|
|
|
365
421
|
// ---------------------------------------------------------------- 运行时 --
|
|
@@ -377,7 +433,7 @@ export async function isDirectorSession(sessionId) {
|
|
|
377
433
|
const openid = openidFromSessionId(sessionId);
|
|
378
434
|
if (!openid) return false;
|
|
379
435
|
const role = await resolveOpenidRuntime(openid);
|
|
380
|
-
return role ?
|
|
436
|
+
return role ? isRoleDirectorSession(role.roleId, sessionId) : false;
|
|
381
437
|
}
|
|
382
438
|
|
|
383
439
|
/** 只读:会话所属角色的工作区路径。未绑定 → null。 */
|
|
@@ -385,7 +441,7 @@ export async function workspaceOfSession(sessionId) {
|
|
|
385
441
|
const openid = openidFromSessionId(sessionId);
|
|
386
442
|
if (!openid) return null;
|
|
387
443
|
const role = await resolveOpenidRuntime(openid);
|
|
388
|
-
return role ? role.workspace : null;
|
|
444
|
+
return role && await isRoleDirectorSession(role.roleId, sessionId) ? role.workspace : null;
|
|
389
445
|
}
|
|
390
446
|
|
|
391
447
|
/**
|
|
@@ -394,33 +450,37 @@ export async function workspaceOfSession(sessionId) {
|
|
|
394
450
|
* 由每个 bot 管线用自己服务的 roleId 调用,避免 openid→单角色查表的歧义。
|
|
395
451
|
*/
|
|
396
452
|
export async function isRoleDirectorSession(roleId, sessionId) {
|
|
453
|
+
const base = String(sessionId ?? '').split('#')[0];
|
|
454
|
+
if (!/^qq:v2:(?:[^:]+:)?c2c:[^:]+$/.test(base)) return false;
|
|
397
455
|
const openid = openidFromSessionId(sessionId);
|
|
398
456
|
if (!openid) return false;
|
|
399
457
|
const role = await loadRole(roleId);
|
|
400
458
|
return role ? role.binding.openid === openid && Boolean(role.persona) : false;
|
|
401
459
|
}
|
|
402
460
|
|
|
403
|
-
/**
|
|
404
|
-
* 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。
|
|
405
|
-
* replaceId
|
|
406
|
-
*/
|
|
407
|
-
export async function scheduleRewake(roleId, minutes, reason, { replaceId } = {}) {
|
|
461
|
+
/**
|
|
462
|
+
* 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。
|
|
463
|
+
* replaceId 只用于替换一次消息参数校验失败时保留下来的兜底安排;普通调用仍可并存多个等待。
|
|
464
|
+
*/
|
|
465
|
+
export async function scheduleRewake(roleId, minutes, reason, { replaceId } = {}) {
|
|
466
|
+
return serializeRole(roleId, async () => {
|
|
408
467
|
const role = await loadRole(roleId);
|
|
409
468
|
if (!role) return { ok: false, atMs: 0, error: '角色不存在' };
|
|
410
469
|
const minutesN = Math.min(Math.max(Number(minutes) || 5, 1), 1440);
|
|
411
|
-
const atMs = Date.now() + minutesN * 60_000;
|
|
412
|
-
const createdAt = Date.now();
|
|
413
|
-
const id = randomBytes(8).toString('hex');
|
|
470
|
+
const atMs = Date.now() + minutesN * 60_000;
|
|
471
|
+
const createdAt = Date.now();
|
|
472
|
+
const id = randomBytes(8).toString('hex');
|
|
414
473
|
// 只保留「尚未到期」的等待;最多保留 MAX_PENDING-1 条旧待唤醒 + 本次,
|
|
415
474
|
// 防止堆积大量未来唤醒来回重复唤醒。(旧记录若曾触发过会在 heartbeat 侧被移除)
|
|
416
475
|
const MAX_PENDING = 5;
|
|
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
|
-
}
|
|
476
|
+
const state = { ...role.state, rewake: role.state.rewake ?? [] };
|
|
477
|
+
const pending = (Array.isArray(state.rewake) ? state.rewake : [])
|
|
478
|
+
.filter((r) => r.atMs > createdAt && (replaceId === undefined || r.id !== replaceId));
|
|
479
|
+
state.rewake = [...pending.slice(-(MAX_PENDING - 1)), { id, atMs, reason: String(reason ?? '').trim() || '到时重新观察当前情境', createdAt }];
|
|
480
|
+
await saveRoleField(roleId, 'state', state);
|
|
481
|
+
return { ok: true, atMs, id };
|
|
482
|
+
});
|
|
483
|
+
}
|
|
424
484
|
|
|
425
485
|
// ---------------------------------------------------------------- 记忆 --
|
|
426
486
|
/** 人设 → memory-root 的 markdown(导演开场读)。 */
|
|
@@ -440,6 +500,8 @@ export function personaMarkdown(persona) {
|
|
|
440
500
|
'',
|
|
441
501
|
'## 说话风格',
|
|
442
502
|
persona.speakingStyle || '(待补充)',
|
|
503
|
+
'',
|
|
504
|
+
'> 语言示例只说明说话方式,不是固定答复,也不表示示例事件已经发生;不可作为共同记忆。',
|
|
443
505
|
].filter((l) => l !== null);
|
|
444
506
|
if (Object.keys(s).length > 0) {
|
|
445
507
|
lines.push('', '## 日程', ...Object.entries(s).map(([k, v]) => `- ${k}: ${v}`));
|
|
@@ -452,7 +514,7 @@ const ABOUT_TA_TEMPLATE = [
|
|
|
452
514
|
'# 关于TA(特殊记忆)',
|
|
453
515
|
'',
|
|
454
516
|
'> 这是你对“TA”的独立记忆:对 TA 的印象、重要事件、TA 的事物。',
|
|
455
|
-
'>
|
|
517
|
+
'> 由你直接编辑维护;日常不需要读写,只在值得记/需要回忆时用 recollect 读取。',
|
|
456
518
|
'> 每次聊天中有值得记住的(TA 的喜好、经历、对你的称呼、重要约定),更新到这里。',
|
|
457
519
|
'> 保持精简、具体,用 TA 自己的说法;不要放设定、不要转述成第三人称旁白。',
|
|
458
520
|
'',
|
|
@@ -466,14 +528,15 @@ const MEMORY_INDEX_TEMPLATE = [
|
|
|
466
528
|
'',
|
|
467
529
|
'> 本文件索引各日期聊天的整体内容,供新会话快速掌握既往情况。',
|
|
468
530
|
'> 由归档任务维护:每归档一个日期,即按叙事三要素(时间、地点、人物)为该日全部事件补写条目,',
|
|
469
|
-
'>
|
|
531
|
+
'> 严格概括、不遗漏信息。保留说话者、知情范围、提议或已确认约定、未消退的情绪及原因。',
|
|
532
|
+
'> 区分实际发生、对方转述、推测和未定事项,保留最近话轮的指代与承接;语言示例不作为事实记录。',
|
|
470
533
|
'',
|
|
471
534
|
'(暂无归档条目。归档后在此按日期补充:**YYYY-MM-DD** — 该日全部事件,每件按 时间|地点|人物|概要 记录)',
|
|
472
535
|
'',
|
|
473
536
|
].join('\n');
|
|
474
537
|
|
|
475
538
|
/** 确保角色记忆目录就绪、人物设定.md 为最新渲染、关于TA.md 与 索引.md 首次就位。 */
|
|
476
|
-
export async function syncRoleMemory(role) {
|
|
539
|
+
export async function syncRoleMemory(role, options = {}) {
|
|
477
540
|
const memory = join(role.workspace, 'memory');
|
|
478
541
|
await mkdir(memory, { recursive: true });
|
|
479
542
|
if (role.persona) {
|
|
@@ -481,7 +544,7 @@ export async function syncRoleMemory(role) {
|
|
|
481
544
|
}
|
|
482
545
|
// 设备文档:角色授权设备 → memory/设备.md(preset 开场读);无授权 → 删除(撤选不残留)。
|
|
483
546
|
const devFile = join(memory, '设备.md');
|
|
484
|
-
const devDoc = await renderDeviceDoc(role);
|
|
547
|
+
const devDoc = await renderDeviceDoc(role, options.renderDevice);
|
|
485
548
|
if (devDoc) {
|
|
486
549
|
await atomicWrite(devFile, devDoc + '\n');
|
|
487
550
|
} else {
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/** 角色会话的创建与恢复;通信实现只提供目标解析,不决定模型或工作区。 */
|
|
2
|
+
import { providerRoute, roleUsesCustomProvider } from './llm-provider.js';
|
|
3
|
+
import { storedSession } from './dsh-runtime.js';
|
|
4
|
+
import { matchesRoleTarget } from './peer-identity.js';
|
|
5
|
+
|
|
6
|
+
export class RoleAgentResolver {
|
|
7
|
+
agentCreation = new Map();
|
|
8
|
+
directorPresetRecorded = new Set();
|
|
9
|
+
constructor(deps, hooks) {
|
|
10
|
+
this.deps = deps;
|
|
11
|
+
this.targetForSession = hooks.targetForSession;
|
|
12
|
+
this.setupAgent = (...args) => hooks.setupAgent?.(...args);
|
|
13
|
+
this.registerSessionContext = (...args) => hooks.registerSessionContext?.(...args);
|
|
14
|
+
}
|
|
15
|
+
async ensureAgent(sessionId) {
|
|
16
|
+
this.deps.signal?.throwIfAborted();
|
|
17
|
+
const agent = await this.resolveAgent(sessionId);
|
|
18
|
+
this.deps.signal?.throwIfAborted();
|
|
19
|
+
return agent;
|
|
20
|
+
}
|
|
21
|
+
async resolveAgent(sessionId) {
|
|
22
|
+
const existing = this.deps.agents.get(sessionId);
|
|
23
|
+
if (existing !== undefined) {
|
|
24
|
+
// 已存在 agent(可能是 dsh 核心路径冷恢复/重组合创建的):若缺
|
|
25
|
+
// pygmalion-director preset 记录,补记 selected 事件,让下一次冷恢复挂对
|
|
26
|
+
// composition;同时补登记会话上下文——standing 导演工具执行时按 sessionId
|
|
27
|
+
// 查 sessionDeps,而核心创建/重组合的 agent 没跑 pygmalion setup。
|
|
28
|
+
void this.recordDirectorPreset(sessionId, existing);
|
|
29
|
+
this.registerSessionContext?.(sessionId);
|
|
30
|
+
return existing;
|
|
31
|
+
}
|
|
32
|
+
let creation = this.agentCreation.get(sessionId);
|
|
33
|
+
if (creation === undefined) {
|
|
34
|
+
this.deps.log.info('Pygmalion ensureAgent: creating agent for %s', sessionId);
|
|
35
|
+
creation = (async () => {
|
|
36
|
+
// 角色运行时:provider/model/cwd 从本 bot 服务的角色配置解析
|
|
37
|
+
//(正式版 Config 无顶层 provider/model/cwd)。
|
|
38
|
+
let provider;
|
|
39
|
+
let model;
|
|
40
|
+
let cwd = process.cwd();
|
|
41
|
+
let isDirector = false;
|
|
42
|
+
if (this.deps.roleId) {
|
|
43
|
+
const role = await this.deps.persona?.loadRole?.(this.deps.roleId);
|
|
44
|
+
if (role) {
|
|
45
|
+
if (roleUsesCustomProvider(role)) {
|
|
46
|
+
const result = await this.deps.prepareRoleProvider?.(role);
|
|
47
|
+
if (!result?.ok) throw new Error(`角色 ${role.roleId} 的自定义模型尚未就绪`);
|
|
48
|
+
}
|
|
49
|
+
await this.deps.persona?.syncRoleMemory?.(role, { renderDevice: this.deps.devices?.document });
|
|
50
|
+
model = role.model.model;
|
|
51
|
+
// provider:apiUrl+apiKey+model 齐(自定义接口)→ 用注册的 route
|
|
52
|
+
//(provider 留空自动 pygmalion-<roleId>,llm-provider.js 已注册);
|
|
53
|
+
// 否则只用角色显式 provider;未配置时明确报错。
|
|
54
|
+
provider = roleUsesCustomProvider(role) ? providerRoute(role) : role.model.provider;
|
|
55
|
+
if (!provider || !model) throw new Error(`角色 ${role.roleId} 未配置可用的 provider/model`);
|
|
56
|
+
cwd = role.workspace;
|
|
57
|
+
// 导演 = c2c 且 openid 已绑定本角色且角色有人设;群/频道走标准模式。
|
|
58
|
+
isDirector = await this.isDirectorSession(sessionId);
|
|
59
|
+
this.deps.log.info('Pygmalion ensureAgent: role %s for %s -> director=%s provider=%s model=%s cwd=%s', this.deps.roleId, sessionId, isDirector, provider, model, cwd);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
throw new Error(`会话所属角色 ${this.deps.roleId} 不存在,禁止使用默认模型`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// No per-user runtime: keep the original behavior of honoring a
|
|
66
|
+
// persisted session cwd before the configured default.
|
|
67
|
+
const snapshot = await storedSession(this.deps.sessionPersistence, sessionId);
|
|
68
|
+
if (!this.deps.roleId && snapshot?.header?.cwd) cwd = snapshot.header.cwd;
|
|
69
|
+
const setup = this.setupAgent !== undefined
|
|
70
|
+
? async (agentCtx, agent) => {
|
|
71
|
+
await this.setupAgent?.(agentCtx, agent);
|
|
72
|
+
}
|
|
73
|
+
: undefined;
|
|
74
|
+
// 导演(Pygmalion)会话:已持久化的会话(重启前聊过)用 resume——resume 会重跑
|
|
75
|
+
// setup 注册最新工具(含此插件刚注册的 life_run 等),并还原历史上下文;
|
|
76
|
+
// 全新会话(无持久化记录)才 create。不能对已有持久化日志的 id 直接 create:
|
|
77
|
+
// dsh 判为 id collision,且该错误在 create 返回后异步抛出,绕开这里的 try/catch。
|
|
78
|
+
if (isDirector) {
|
|
79
|
+
const persisted = snapshot !== undefined;
|
|
80
|
+
// meta.agentPreset 写进 session header:冷重启后任何恢复路径(含 dsh
|
|
81
|
+
// 核心 api-proxy)经 resolveSessionPreset 都会挂 pygmalion-director,
|
|
82
|
+
// 否则挂 standard 默认 composition → director_send 等工具缺失。
|
|
83
|
+
const createOpts = { sessionId, agentOptions: { provider, model }, meta: { cwd, agentPreset: 'pygmalion-director' } };
|
|
84
|
+
const resumeOpts = { resumeSessionId: sessionId, agentOptions: { provider, model } };
|
|
85
|
+
try {
|
|
86
|
+
const agent = persisted
|
|
87
|
+
? (await this.deps.agents.resume({ ...resumeOpts, ...(setup !== undefined ? { setup } : {}) })).agent
|
|
88
|
+
: (await this.deps.agents.create({ ...createOpts, ...(setup !== undefined ? { setup } : {}) })).agent;
|
|
89
|
+
await this.recordDirectorPreset(sessionId, agent);
|
|
90
|
+
this.deps.log.info('Pygmalion ensureAgent: director %s %s (tools registered)', persisted ? 'resumed' : 'created', agent.id);
|
|
91
|
+
return agent;
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
this.deps.log.error('角色会话恢复/创建失败,保留历史并停止本次交互: %o', error);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (snapshot !== undefined) {
|
|
99
|
+
return (await this.deps.agents.resume({
|
|
100
|
+
resumeSessionId: sessionId,
|
|
101
|
+
agentOptions: { provider, model },
|
|
102
|
+
...(setup !== undefined ? { setup } : {}),
|
|
103
|
+
})).agent;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const agent = (await this.deps.agents.create({
|
|
107
|
+
sessionId,
|
|
108
|
+
agentOptions: { provider, model },
|
|
109
|
+
meta: { cwd },
|
|
110
|
+
...(setup !== undefined ? { setup } : {}),
|
|
111
|
+
})).agent;
|
|
112
|
+
this.deps.log.info('Pygmalion ensureAgent: created %s', agent.id);
|
|
113
|
+
return agent;
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
this.deps.log.error('Role session %s could not be created (cwd=%s): %o', sessionId, cwd, error);
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
this.agentCreation.set(sessionId, creation);
|
|
121
|
+
void creation.then(() => { this.agentCreation.delete(sessionId); }, () => { this.agentCreation.delete(sessionId); });
|
|
122
|
+
}
|
|
123
|
+
return creation;
|
|
124
|
+
}
|
|
125
|
+
/** 该会话是否属于「本 bot 服务的角色」的 c2c 导演会话(与 ensureAgent 判定一致)。 */
|
|
126
|
+
async isDirectorSession(sessionId) {
|
|
127
|
+
if (!this.deps.roleId || this.deps.persona?.loadRole === undefined)
|
|
128
|
+
return false;
|
|
129
|
+
const role = await this.deps.persona.loadRole(this.deps.roleId);
|
|
130
|
+
if (!role)
|
|
131
|
+
return false;
|
|
132
|
+
return Boolean(role.persona) && matchesRoleTarget(role, this.targetForSession(sessionId), this.deps.identityScope);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 确保导演会话的持久化记录 agentPreset='pygmalion-director':补记
|
|
136
|
+
* agent-preset/selected 事件。dsh 冷恢复(含核心 api-proxy 路径)经
|
|
137
|
+
* resolveSessionPreset 决定挂哪个 preset,header 无 agentPreset、日志无
|
|
138
|
+
* selected 事件时回退 standard 默认 composition → director_send 等工具缺失。
|
|
139
|
+
* 每进程每会话只补记一次。
|
|
140
|
+
*/
|
|
141
|
+
async recordDirectorPreset(sessionId, agent) {
|
|
142
|
+
if (agent === undefined || this.directorPresetRecorded.has(sessionId))
|
|
143
|
+
return;
|
|
144
|
+
if (!(await this.isDirectorSession(sessionId)))
|
|
145
|
+
return;
|
|
146
|
+
this.directorPresetRecorded.add(sessionId);
|
|
147
|
+
try {
|
|
148
|
+
agent.session.append('agent-preset/selected', { agentPreset: 'pygmalion-director' });
|
|
149
|
+
this.deps.log.info('Pygmalion ensureAgent: 补记导演 preset 到 %s (agent-preset/selected)', sessionId);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
this.deps.log.warn('Pygmalion ensureAgent: 补记导演 preset 失败 %s: %o', sessionId, error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** 单角色运行时:统一会话依赖、恢复、交付取消与内部唤醒;不处理通信协议。 */
|
|
2
|
+
import { RoleAgentResolver } from './role-agent.js';
|
|
3
|
+
import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
|
|
4
|
+
import { createRoleDeliveryGuard } from './delivery-scope.js';
|
|
5
|
+
import { bindingStamp, matchesRoleTarget } from './peer-identity.js';
|
|
6
|
+
import { wakeupSession } from './wakeup.js';
|
|
7
|
+
|
|
8
|
+
export function createRoleRuntime(deps, connection, transport) {
|
|
9
|
+
const lifetime = new AbortController();
|
|
10
|
+
const { persona } = deps;
|
|
11
|
+
const director = deps.director?.get?.('pygmalion.director');
|
|
12
|
+
const roleId = connection.roleId;
|
|
13
|
+
const beginDelivery = createRoleDeliveryGuard({ persona, roleId, signal: lifetime.signal, identityScope: transport.identityScope });
|
|
14
|
+
const setupDeps = { ...deps, ...transport, roleId, beginDelivery,
|
|
15
|
+
httpApiToken: connection.httpApiToken, httpApiPath: connection.httpApiPath,
|
|
16
|
+
resolvePreset: deps.agentPresets ? async id => {
|
|
17
|
+
const role = await persona.loadRole(roleId);
|
|
18
|
+
const preset = matchesRoleTarget(role, transport.targetForSession(id), transport.identityScope)
|
|
19
|
+
? 'pygmalion-director' : connection.agentPreset || 'standard';
|
|
20
|
+
return deps.agentPresets.resolve(transport.threads.presetFor(id) ?? preset);
|
|
21
|
+
} : undefined,
|
|
22
|
+
};
|
|
23
|
+
const setupAgent = createSetupAgent(setupDeps);
|
|
24
|
+
const sessionIds = new Set();
|
|
25
|
+
const registerSessionContext = id => {
|
|
26
|
+
lifetime.signal.throwIfAborted(); sessionIds.add(id);
|
|
27
|
+
director?.registerSession?.(id, buildSessionDeps(setupDeps, id));
|
|
28
|
+
};
|
|
29
|
+
const roleAgents = new RoleAgentResolver({ ...deps, roleId, signal: lifetime.signal, identityScope: transport.identityScope },
|
|
30
|
+
{ targetForSession: transport.targetForSession, setupAgent, registerSessionContext });
|
|
31
|
+
// 冷恢复依赖也来自同一入口;目标由持久化路由或适配器的旧格式兼容解析。
|
|
32
|
+
director?.registerSessionBuilder?.(connection.id, id => {
|
|
33
|
+
lifetime.signal.throwIfAborted(); sessionIds.add(id); return buildSessionDeps(setupDeps, id);
|
|
34
|
+
});
|
|
35
|
+
async function boundTarget(role = undefined) {
|
|
36
|
+
role ??= await persona.loadRole(roleId);
|
|
37
|
+
const target = await transport.targetForRole(role);
|
|
38
|
+
return matchesRoleTarget(role, target, transport.identityScope) ? target : undefined;
|
|
39
|
+
}
|
|
40
|
+
async function wake(params = {}) {
|
|
41
|
+
const role = await persona.loadRole(roleId);
|
|
42
|
+
const target = await boundTarget(role);
|
|
43
|
+
if (!target) return { ok: false, error: '角色尚无当前连接的聊天绑定' };
|
|
44
|
+
const attempt = await beginDelivery(target);
|
|
45
|
+
return wakeupSession({ ...deps, ...transport, roleId, botId: connection.id,
|
|
46
|
+
ensureAgent: id => roleAgents.ensureAgent(id), assertCurrent: async () => {
|
|
47
|
+
await attempt.assertCurrent();
|
|
48
|
+
if(bindingStamp(await persona.loadRole(roleId))!==bindingStamp(role))throw new Error('角色绑定已改变');
|
|
49
|
+
},
|
|
50
|
+
withinChatWindowMs: connection.withinChatWindowMs }, { ...params, target });
|
|
51
|
+
}
|
|
52
|
+
return { setupDeps, setupAgent, registerSessionContext, roleAgents, beginDelivery, boundTarget, wake,
|
|
53
|
+
signal: lifetime.signal,
|
|
54
|
+
start() {
|
|
55
|
+
deps.devices?.registerRole?.(roleId, (contextText, { priority = false } = {}) => wake({ reason: '设备事件', contextText,
|
|
56
|
+
force: priority, interruptTool: priority ? 'director_send' : undefined }));
|
|
57
|
+
},
|
|
58
|
+
dispose() {
|
|
59
|
+
lifetime.abort(new Error('角色连接已停止,本次交互已取消'));
|
|
60
|
+
for (const id of sessionIds) director?.unregisterSession?.(id);
|
|
61
|
+
director?.unregisterSessionBuilder?.(connection.id);
|
|
62
|
+
deps.devices?.unregisterRole?.(roleId);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** 独立角色生成配置;旧数据没有此文件时保持原有单模型行为。 */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
export class RoleplayConfigError extends Error { constructor(message) { super(message); this.name='RoleplayConfigError'; } }
|
|
4
|
+
export const DEFAULT_ROLEPLAY = Object.freeze({ enabled: false, provider: '', model: '', apiUrl: '', apiKey: '',
|
|
5
|
+
reasoningEffort: '', retries: 2, maxInputChars: 500000 });
|
|
6
|
+
|
|
7
|
+
export function normalizeRoleplayConfig(value = {}) {
|
|
8
|
+
const result = { ...DEFAULT_ROLEPLAY };
|
|
9
|
+
for (const key of ['provider', 'model', 'apiUrl', 'apiKey', 'reasoningEffort']) {
|
|
10
|
+
if (value[key] !== undefined && typeof value[key] !== 'string') throw new RoleplayConfigError(`角色生成 ${key} 必须是字符串`);
|
|
11
|
+
if (typeof value[key] === 'string') result[key] = value[key].trim();
|
|
12
|
+
}
|
|
13
|
+
if (value.enabled !== undefined && typeof value.enabled !== 'boolean') throw new RoleplayConfigError('角色生成开关必须是布尔值');
|
|
14
|
+
result.enabled = value.enabled === true;
|
|
15
|
+
// 旧版写入的 timeoutMs、maxTokens 不再读取;插件不设置生成时限或输出 token 上限。
|
|
16
|
+
for (const [key, min, max] of [['retries', 0, 3], ['maxInputChars', 1000, 2000000]]) {
|
|
17
|
+
if (value[key] === undefined) continue;
|
|
18
|
+
if (!Number.isInteger(value[key]) || value[key] < min || value[key] > max) throw new RoleplayConfigError(`角色生成 ${key} 须为 ${min}–${max} 的整数`);
|
|
19
|
+
result[key] = value[key];
|
|
20
|
+
}
|
|
21
|
+
if (result.apiUrl) {
|
|
22
|
+
let url; try { url = new URL(result.apiUrl); } catch { throw new RoleplayConfigError('角色生成 API 地址无效'); }
|
|
23
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new RoleplayConfigError('角色生成 API 地址须为无内嵌凭据的 HTTP(S) 地址');
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function validateEnabledRoleplay(config) {
|
|
29
|
+
if (!config.enabled) return;
|
|
30
|
+
if (!config.model || !(config.apiUrl ? config.apiKey : config.provider)) throw new RoleplayConfigError('启用角色生成前须配置模型,以及 Provider 或独立 API 地址和密钥');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function publicRoleplayConfig(value) {
|
|
34
|
+
const { apiKey, ...config } = normalizeRoleplayConfig(value);
|
|
35
|
+
return { ...config, keyConfigured: Boolean(apiKey) };
|
|
36
|
+
}
|
|
37
|
+
export const roleplayConfigSignature = value => createHash('sha256').update(JSON.stringify(normalizeRoleplayConfig(value))).digest('hex');
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** 模型输入只需可读的来源分块;比较完整文本后选择较短格式。 */
|
|
2
|
+
const xml=text=>String(text).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>');
|
|
3
|
+
const attribute=text=>xml(text).replaceAll('"','"');
|
|
4
|
+
const pad=n=>String(n).padStart(2,'0');
|
|
5
|
+
export function roleplayTime(value,{minute=false}={}){
|
|
6
|
+
if(value===null||value===undefined||!Number.isFinite(Number(value)))return '';
|
|
7
|
+
const date=new Date(Number(value));if(Number.isNaN(date.getTime()))return '';
|
|
8
|
+
return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}${minute?'':':'+pad(date.getSeconds())}`;
|
|
9
|
+
}
|
|
10
|
+
export function lastUserMessageNotice(value,now){
|
|
11
|
+
const time=roleplayTime(value,{minute:true});if(!time)return '';
|
|
12
|
+
const today=roleplayTime(now,{minute:true}).slice(0,10);
|
|
13
|
+
return `用户的上一条消息发送于${time.slice(0,10)===today?time.slice(11):time}。`;
|
|
14
|
+
}
|
|
15
|
+
export function formatParallelPacket(packet){
|
|
16
|
+
const markdown=[],tags=[];
|
|
17
|
+
if(packet.initialization){markdown.push('# 初始化');tags.push('<initialization/>');}
|
|
18
|
+
for(const file of packet.files){
|
|
19
|
+
const mode=file.mode==='alias'?`同文 ${file.aliasOf}@v${file.aliasVersion}`:file.mode==='append'?'追加':'全文';
|
|
20
|
+
const omission=file.omitted?`;省略已有往来 ${file.omitted} 条`:'';
|
|
21
|
+
markdown.push(`## 文件 ${file.path} · v${file.version} · ${mode}${omission}${file.content?'\n'+file.content:''}`);
|
|
22
|
+
const attrs=`path="${attribute(file.path)}" v="${file.version}" mode="${file.mode}"${file.mode==='alias'?` of="${attribute(file.aliasOf)}" version="${file.aliasVersion}"`:''}${file.omitted?` omit="${file.omitted}"`:''}`;
|
|
23
|
+
tags.push(file.content?`<file ${attrs}>\n${xml(file.content)}${file.content.endsWith('\n')?'':'\n'}</file>`:`<file ${attrs}/>`);
|
|
24
|
+
}
|
|
25
|
+
const changed=new Set(packet.files.map(file=>file.path));
|
|
26
|
+
const references=packet.references.filter(path=>!changed.has(path));
|
|
27
|
+
if(references.length){markdown.push('## 引用\n'+references.join('\n'));tags.push('<references>\n'+references.map(xml).join('\n')+'\n</references>');}
|
|
28
|
+
for(const record of packet.conversation){
|
|
29
|
+
const time=roleplayTime(record.time),speaker=record.speaker==='user'?'用户':'角色';
|
|
30
|
+
markdown.push(`## ${speaker}${time?' '+time:''}\n${record.text}`);
|
|
31
|
+
const tag=record.speaker==='user'?'user':'character';tags.push(`<${tag}${time?` time="${time}"`:''}>\n${xml(record.text)}${record.text.endsWith('\n')?'':'\n'}</${tag}>`);
|
|
32
|
+
}
|
|
33
|
+
markdown.push('## 额外事实\n'+packet.additionalInformation);
|
|
34
|
+
tags.push('<facts>\n'+xml(packet.additionalInformation)+(packet.additionalInformation.endsWith('\n')?'':'\n')+'</facts>');
|
|
35
|
+
const md=markdown.join('\n\n'),flatXml=tags.join('\n');
|
|
36
|
+
return {text:md.length<=flatXml.length?md:flatXml,format:md.length<=flatXml.length?'markdown':'xml',lengths:{markdown:md.length,xml:flatXml.length}};
|
|
37
|
+
}
|