pygmalion 0.1.15 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +63 -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 +36 -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 +128 -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/inbound.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { transcribe } from './speech-input.js';
|
|
1
2
|
/**
|
|
2
3
|
* Inbound pipeline (QQ → DSH agent): normalize the gateway event, dedupe,
|
|
3
4
|
* enforce the allowlist, strip @mentions, resolve quoted messages via the
|
|
@@ -11,9 +12,8 @@ import { join } from 'node:path';
|
|
|
11
12
|
import { targetKey } from './threads.js';
|
|
12
13
|
import { listLifeScripts, listRunningLifeScripts } from './agent-life.js';
|
|
13
14
|
import { isRoleDirectorSession } from './persona.js';
|
|
14
|
-
import { sessionFileFor } from './active-session.js';
|
|
15
15
|
import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
|
|
16
|
-
import {
|
|
16
|
+
import { RoleAgentResolver } from './role-agent.js';
|
|
17
17
|
export const SESSION_PREFIX = 'qq:v2';
|
|
18
18
|
/** LRU caps for inbound dedup. */
|
|
19
19
|
const DEDUP_MAX = 2_000;
|
|
@@ -163,7 +163,9 @@ export function baseSessionId(target, botId) {
|
|
|
163
163
|
}
|
|
164
164
|
/** Session id used by the DSH agent for a given target+thread. */
|
|
165
165
|
export function effectiveSessionId(target, thread, botId) {
|
|
166
|
-
|
|
166
|
+
// 新宿主使用独立会话代际;旧会话不转换、不覆盖,长期记忆仍在同一角色工作区。
|
|
167
|
+
const base = `${baseSessionId(target, botId)}#dsh021`;
|
|
168
|
+
return thread === 0 ? base : `${base}#n${thread}`;
|
|
167
169
|
}
|
|
168
170
|
/** Compatibility shim: returns the base id (thread 0) for the inbound message. */
|
|
169
171
|
export function sessionIdFor(message, botId) {
|
|
@@ -281,37 +283,16 @@ async function saveInboundImage(mediaDir, bytes, mediaType, filename) {
|
|
|
281
283
|
return path;
|
|
282
284
|
}
|
|
283
285
|
/** OpenAI-compatible speech-to-text transcription (skipped without an apiKey). */
|
|
284
|
-
async function transcribe(stt, wavPath) {
|
|
285
|
-
if (stt.apiKey === undefined || stt.apiKey.length === 0)
|
|
286
|
-
return undefined;
|
|
287
|
-
const { readFile } = await import('node:fs/promises');
|
|
288
|
-
const form = new FormData();
|
|
289
|
-
form.append('file', new Blob([await readFile(wavPath)]), 'audio.wav');
|
|
290
|
-
form.append('model', stt.model);
|
|
291
|
-
const base = stt.baseUrl.replace(/\/+$/, '');
|
|
292
|
-
const response = await fetch(`${base}/audio/transcriptions`, {
|
|
293
|
-
method: 'POST',
|
|
294
|
-
headers: { Authorization: `Bearer ${stt.apiKey}` },
|
|
295
|
-
body: form,
|
|
296
|
-
signal: AbortSignal.timeout(60_000),
|
|
297
|
-
});
|
|
298
|
-
if (!response.ok)
|
|
299
|
-
return undefined;
|
|
300
|
-
const data = asRecord(await response.json());
|
|
301
|
-
return typeof data?.text === 'string' ? data.text : undefined;
|
|
302
|
-
}
|
|
303
286
|
/** The inbound pipeline. */
|
|
304
287
|
export class InboundPipeline {
|
|
305
288
|
deps;
|
|
306
289
|
seen = new Set();
|
|
307
290
|
seenOrder = [];
|
|
308
|
-
agentCreation = new Map();
|
|
309
291
|
/** Per-session C2C typing indicator timers; cleared on turn end / disposal. */
|
|
310
292
|
typingTimers = new Map();
|
|
311
293
|
/** Per-session last user-activity timestamp (for Pygmalion collision detection). */
|
|
312
294
|
lastActivity = new Map();
|
|
313
295
|
/** 每进程每导演会话只补记一次 agent-preset/selected(避免反复 append)。 */
|
|
314
|
-
directorPresetRecorded = new Set();
|
|
315
296
|
/** Attached after construction so the handlers can close over outbound. */
|
|
316
297
|
onSlashCommand;
|
|
317
298
|
setupAgent;
|
|
@@ -319,6 +300,11 @@ export class InboundPipeline {
|
|
|
319
300
|
registerSessionContext;
|
|
320
301
|
constructor(deps) {
|
|
321
302
|
this.deps = deps;
|
|
303
|
+
this.roleAgents = new RoleAgentResolver(deps, {
|
|
304
|
+
targetForSession: id => deps.routes.get(id)?.target ?? targetOfSession(id),
|
|
305
|
+
setupAgent: (...args) => this.setupAgent?.(...args),
|
|
306
|
+
registerSessionContext: (...args) => this.registerSessionContext?.(...args),
|
|
307
|
+
});
|
|
322
308
|
}
|
|
323
309
|
/**
|
|
324
310
|
* Attach the slash-command and per-agent setup callbacks after the
|
|
@@ -343,12 +329,11 @@ export class InboundPipeline {
|
|
|
343
329
|
if (!persona?.roleWorkspace || !roleId || !sessionId)
|
|
344
330
|
return;
|
|
345
331
|
const workspace = persona.roleWorkspace(roleId);
|
|
346
|
-
const file = sessionFileFor({ sessionId, workspace });
|
|
347
332
|
setTimeout(() => {
|
|
348
333
|
void (async () => {
|
|
349
334
|
try {
|
|
350
335
|
const charLabel = await charLabelOf(persona, roleId);
|
|
351
|
-
await refreshRawRecordFromSession({ workspace,
|
|
336
|
+
await refreshRawRecordFromSession({ workspace, sessionId, persistence: this.deps.sessionPersistence, charLabel, log });
|
|
352
337
|
}
|
|
353
338
|
catch (error) {
|
|
354
339
|
log?.warn?.('pygmalion: 刷新原始记录失败: %o', error);
|
|
@@ -371,8 +356,13 @@ export class InboundPipeline {
|
|
|
371
356
|
// openid 绑定校验(修 D5):c2c 消息按本 bot 服务的角色绑定/校验拥有者。
|
|
372
357
|
// 未绑定 → 首聊自动绑定为角色拥有者;已绑定同 openid → 放行;已绑定不同 → 拒绝。
|
|
373
358
|
// 群/频道消息无单拥有者概念,跳过绑定校验(仍受 groupAllowFrom 白名单约束)。
|
|
359
|
+
let accepted;
|
|
374
360
|
if (message.kind === 'c2c' && this.deps.roleId && this.deps.persona?.bindRoleOpenid !== undefined) {
|
|
375
|
-
const bind =
|
|
361
|
+
const bind = this.deps.acceptIncoming
|
|
362
|
+
? await this.deps.acceptIncoming(message)
|
|
363
|
+
: await this.deps.persona.bindRoleOpenid(this.deps.roleId, message.senderId, this.deps.botAppId);
|
|
364
|
+
if (!bind) return;
|
|
365
|
+
accepted = bind;
|
|
376
366
|
if (bind.status === 'mismatch') {
|
|
377
367
|
this.deps.log.warn('QQ inbound: openid %s rejected for role %s (bound to %s)', message.senderId, this.deps.roleId, bind.role?.binding?.openid);
|
|
378
368
|
return;
|
|
@@ -513,21 +503,13 @@ export class InboundPipeline {
|
|
|
513
503
|
extras.unshift(running.length
|
|
514
504
|
? `[生活脚本] 有脚本在跑(${running.map((r) => r.scriptName).join('、')}),非零已满足。`
|
|
515
505
|
: scripts.length
|
|
516
|
-
? `[生活脚本] life/ 下有脚本(${scripts.join('、')})但当前都没有在跑——想保留主动关心用户的可能,可用 life_run 重启一个。`
|
|
517
|
-
: '[生活脚本] life/ 当前没有任何脚本在跑(不满足“非零”)。若想保留主动关心用户的可能,可新建一个你的脚本(新文件,勿覆盖已有文件)并用 life_run 运行。');
|
|
506
|
+
? `[生活脚本] life/ 下有脚本(${scripts.join('、')})但当前都没有在跑——想保留主动关心用户的可能,可用 life_run 重启一个。`
|
|
507
|
+
: '[生活脚本] life/ 当前没有任何脚本在跑(不满足“非零”)。若想保留主动关心用户的可能,可新建一个你的脚本(新文件,勿覆盖已有文件)并用 life_run 运行。');
|
|
518
508
|
}
|
|
519
509
|
} catch (e) { this.deps.log.warn('life script hint failed: %o', e); }
|
|
520
510
|
}
|
|
521
|
-
// 身份提醒:多轮后 dsh 容易把自己当成角色本人,每轮给导演会话补一句边界提示。
|
|
522
|
-
// 走 extras 行(标记 [身份提醒]),记忆提取(cleanUserText)会剥离,不污染原始记录。
|
|
523
|
-
if (this.deps.roleId && this.deps.persona?.roleWorkspace) {
|
|
524
|
-
try {
|
|
525
|
-
if (await isRoleDirectorSession(this.deps.roleId, sessionId))
|
|
526
|
-
extras.unshift('[身份提醒] 这条 QQ 消息发给角色,不是发给导演;你只在幕后决定角色如何回应,角色发言只走 director_send。');
|
|
527
|
-
} catch (e) { this.deps.log.warn('identity hint failed: %o', e); }
|
|
528
|
-
}
|
|
529
511
|
// 设备分享链接激活(仅 c2c 拥有者会话):识别 MonsterParty 链接 → 解析 → 激活该角色设备;
|
|
530
|
-
//
|
|
512
|
+
// 驱动匹配的凭据输入从模型文本剥掉(单次敏感凭证,不喂模型/不进记忆)。
|
|
531
513
|
let consumedLinkRaw = null;
|
|
532
514
|
if (message.kind === 'c2c' && this.deps.roleId && this.deps.persona && this.deps.devices) {
|
|
533
515
|
try {
|
|
@@ -535,17 +517,11 @@ export class InboundPipeline {
|
|
|
535
517
|
const scan = [message.content,
|
|
536
518
|
...message.msgElements.map((e) => e?.content ?? ''),
|
|
537
519
|
...message.msgElements.map((e) => e?.url ?? '')].join('\n');
|
|
538
|
-
const
|
|
539
|
-
if (
|
|
540
|
-
|
|
541
|
-
if (
|
|
542
|
-
|
|
543
|
-
extras.unshift(`[设备] 「${r.alias}」已通过你发来的分享链接激活。操控方式见 memory/设备.md。`);
|
|
544
|
-
} else if (r.code === 'no-device') {
|
|
545
|
-
await this.deps.api.sendText(message.reply, '你还没给这个角色配可用设备:请到管理台「我的设备」登记设备并为角色勾选,然后再发一次分享链接。', message.id).catch(() => {});
|
|
546
|
-
} else if (r.code !== 'not-owner') {
|
|
547
|
-
await this.deps.api.sendText(message.reply, '设备分享链接无效或已过期,请重新生成后再发。', message.id).catch(() => {});
|
|
548
|
-
}
|
|
520
|
+
const result = await this.deps.devices.handleInput?.(this.deps.roleId, scan, { openid: message.senderId });
|
|
521
|
+
if (result) {
|
|
522
|
+
consumedLinkRaw = result.raw;
|
|
523
|
+
if (result.ok) extras.unshift(`[设备] 「${result.alias}」已完成驱动要求的接入。使用前加载 ${result.skill} skill。`);
|
|
524
|
+
else extras.unshift('[设备] 驱动未接受此次输入,设备尚未就绪。请核对对应驱动的 skill 与管理页授权。');
|
|
549
525
|
}
|
|
550
526
|
}
|
|
551
527
|
} catch (e) { this.deps.log.warn('device activate failed: %o', e); }
|
|
@@ -555,6 +531,10 @@ export class InboundPipeline {
|
|
|
555
531
|
this.stopTyping(sessionId);
|
|
556
532
|
return;
|
|
557
533
|
}
|
|
534
|
+
if (accepted?.deliver) {
|
|
535
|
+
await accepted.deliver([...(text.length ? [{ type: 'text', text }] : []), ...imageBlocks], Number.isNaN(msgTs) ? undefined : msgTs);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
558
538
|
const agent = await this.ensureAgent(sessionId);
|
|
559
539
|
if (!agent) {
|
|
560
540
|
this.deps.log.error('QQ inbound: ensureAgent returned no agent for %s', sessionId);
|
|
@@ -569,7 +549,7 @@ export class InboundPipeline {
|
|
|
569
549
|
...(text.length > 0 ? [{ type: 'text', text }] : []),
|
|
570
550
|
...imageBlocks,
|
|
571
551
|
],
|
|
572
|
-
source: { kind: 'user',
|
|
552
|
+
source: { kind: 'user', rpcId: `pygmalion.qq:${message.id}`, ...(Number.isNaN(msgTs)?{}:{sentAt:msgTs}) },
|
|
573
553
|
}, 'next-turn', true);
|
|
574
554
|
// 日期层记忆:消息送达后延迟从活跃会话 session log 提取写原始记录(仅 c2c 拥有者会话)。
|
|
575
555
|
if (message.kind === 'c2c')
|
|
@@ -612,161 +592,10 @@ export class InboundPipeline {
|
|
|
612
592
|
* from the user's config/binding, workspace = <data>/users/<openid>/workspace)
|
|
613
593
|
* so every user runs on their own model and memory space.
|
|
614
594
|
*/
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
// pygmalion-director preset 记录,补记 selected 事件,让下一次冷恢复挂对
|
|
620
|
-
// composition;同时补登记会话上下文——standing 导演工具执行时按 sessionId
|
|
621
|
-
// 查 sessionDeps,而核心创建/重组合的 agent 没跑 pygmalion setup。
|
|
622
|
-
void this.recordDirectorPreset(sessionId, existing);
|
|
623
|
-
this.registerSessionContext?.(sessionId);
|
|
624
|
-
return existing;
|
|
625
|
-
}
|
|
626
|
-
let creation = this.agentCreation.get(sessionId);
|
|
627
|
-
if (creation === undefined) {
|
|
628
|
-
this.deps.log.info('QQ ensureAgent: creating agent for %s', sessionId);
|
|
629
|
-
creation = (async () => {
|
|
630
|
-
// 角色运行时:provider/model/cwd 从本 bot 服务的角色配置解析
|
|
631
|
-
//(正式版 Config 无顶层 provider/model/cwd)。
|
|
632
|
-
let provider;
|
|
633
|
-
let model;
|
|
634
|
-
let cwd = process.cwd();
|
|
635
|
-
let isDirector = false;
|
|
636
|
-
if (this.deps.roleId) {
|
|
637
|
-
const role = await this.deps.persona?.loadRole?.(this.deps.roleId);
|
|
638
|
-
if (role) {
|
|
639
|
-
await this.deps.persona?.syncRoleMemory?.(role);
|
|
640
|
-
model = role.model.model;
|
|
641
|
-
// provider:apiUrl+apiKey+model 齐(自定义接口)→ 用注册的 route
|
|
642
|
-
//(provider 留空自动 pygmalion-<roleId>,llm-provider.js 已注册);
|
|
643
|
-
// 否则用显式 provider;再留空回退内置默认 opencode-go。
|
|
644
|
-
provider = roleUsesCustomProvider(role) ? providerRoute(role) : (role.model.provider || 'opencode-go');
|
|
645
|
-
cwd = role.workspace;
|
|
646
|
-
// 导演 = c2c 且 openid 已绑定本角色且角色有人设;群/频道走标准模式。
|
|
647
|
-
const openid = this.deps.persona?.openidFromSessionId?.(sessionId);
|
|
648
|
-
isDirector = openid !== undefined && openid === role.binding.openid && Boolean(role.persona);
|
|
649
|
-
this.deps.log.info('QQ ensureAgent: role %s for %s -> director=%s provider=%s model=%s cwd=%s', this.deps.roleId, sessionId, isDirector, provider, model, cwd);
|
|
650
|
-
}
|
|
651
|
-
else {
|
|
652
|
-
this.deps.log.warn('QQ ensureAgent: role %s missing, session %s falls back to default runtime', this.deps.roleId, sessionId);
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
// No per-user runtime: keep the original behavior of honoring a
|
|
656
|
-
// persisted session cwd before the configured default.
|
|
657
|
-
if (this.deps.roleId === undefined && this.deps.sessionPersistence !== undefined) {
|
|
658
|
-
try {
|
|
659
|
-
const inspected = await this.deps.sessionPersistence.inspect(sessionId);
|
|
660
|
-
if (typeof inspected.meta.cwd === 'string' && inspected.meta.cwd.length > 0)
|
|
661
|
-
cwd = inspected.meta.cwd;
|
|
662
|
-
}
|
|
663
|
-
catch {
|
|
664
|
-
// No persisted session: fall through with the configured cwd.
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
const setup = this.setupAgent !== undefined
|
|
668
|
-
? async (agentCtx) => {
|
|
669
|
-
await this.setupAgent?.(agentCtx, sessionId);
|
|
670
|
-
}
|
|
671
|
-
: undefined;
|
|
672
|
-
// 导演(Pygmalion)会话:已持久化的会话(重启前聊过)用 resume——resume 会重跑
|
|
673
|
-
// setup 注册最新工具(含此插件刚注册的 life_run 等),并还原历史上下文;
|
|
674
|
-
// 全新会话(无持久化记录)才 create。不能对已有持久化日志的 id 直接 create:
|
|
675
|
-
// dsh 判为 id collision,且该错误在 create 返回后异步抛出,绕开这里的 try/catch。
|
|
676
|
-
if (isDirector) {
|
|
677
|
-
const persisted = this.deps.sessionPersistence !== undefined
|
|
678
|
-
? await this.deps.sessionPersistence.inspect(sessionId).then(() => true).catch(() => false)
|
|
679
|
-
: false;
|
|
680
|
-
// meta.agentPreset 写进 session header:冷重启后任何恢复路径(含 dsh
|
|
681
|
-
// 核心 api-proxy)经 resolveSessionPreset 都会挂 pygmalion-director,
|
|
682
|
-
// 否则挂 standard 默认 composition → director_send 等工具缺失。
|
|
683
|
-
const createOpts = { sessionId, agentOptions: { provider, model }, meta: { cwd, agentPreset: 'pygmalion-director' } };
|
|
684
|
-
const resumeOpts = { resumeSessionId: sessionId, agentOptions: { provider, model } };
|
|
685
|
-
try {
|
|
686
|
-
const agent = persisted
|
|
687
|
-
? (await this.deps.agents.resume({ ...resumeOpts, ...(setup !== undefined ? { setup } : {}) })).agent
|
|
688
|
-
: (await this.deps.agents.create({ ...createOpts, ...(setup !== undefined ? { setup } : {}) })).agent;
|
|
689
|
-
await this.recordDirectorPreset(sessionId, agent);
|
|
690
|
-
this.deps.log.info('QQ ensureAgent: director %s %s (tools registered)', persisted ? 'resumed' : 'created', agent.id);
|
|
691
|
-
return agent;
|
|
692
|
-
}
|
|
693
|
-
catch (error) {
|
|
694
|
-
this.deps.log.error('QQ ensureAgent: director %s for %s failed, swap fallback: %o', persisted ? 'resume' : 'create', sessionId, error);
|
|
695
|
-
try {
|
|
696
|
-
const agent = persisted
|
|
697
|
-
? (await this.deps.agents.create({ ...createOpts, ...(setup !== undefined ? { setup } : {}) })).agent
|
|
698
|
-
: (await this.deps.agents.resume({ ...resumeOpts, ...(setup !== undefined ? { setup } : {}) })).agent;
|
|
699
|
-
await this.recordDirectorPreset(sessionId, agent);
|
|
700
|
-
return agent;
|
|
701
|
-
}
|
|
702
|
-
catch (swapError) {
|
|
703
|
-
this.deps.log.error('QQ director session %s could not be created/resumed: %o', sessionId, swapError);
|
|
704
|
-
throw swapError;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
try {
|
|
709
|
-
return (await this.deps.agents.resume({
|
|
710
|
-
resumeSessionId: sessionId,
|
|
711
|
-
agentOptions: { provider, model },
|
|
712
|
-
...(setup !== undefined ? { setup } : {}),
|
|
713
|
-
})).agent;
|
|
714
|
-
}
|
|
715
|
-
catch (error) {
|
|
716
|
-
if (this.deps.config.debug)
|
|
717
|
-
this.deps.log.debug?.('resume %s failed, creating fresh: %o', sessionId, error);
|
|
718
|
-
}
|
|
719
|
-
try {
|
|
720
|
-
const agent = (await this.deps.agents.create({
|
|
721
|
-
sessionId,
|
|
722
|
-
agentOptions: { provider, model },
|
|
723
|
-
meta: { cwd },
|
|
724
|
-
...(setup !== undefined ? { setup } : {}),
|
|
725
|
-
})).agent;
|
|
726
|
-
this.deps.log.info('QQ ensureAgent: created %s', agent.id);
|
|
727
|
-
return agent;
|
|
728
|
-
}
|
|
729
|
-
catch (error) {
|
|
730
|
-
this.deps.log.error('QQ session %s could not be created (cwd=%s): %o', sessionId, cwd, error);
|
|
731
|
-
throw error;
|
|
732
|
-
}
|
|
733
|
-
})();
|
|
734
|
-
this.agentCreation.set(sessionId, creation);
|
|
735
|
-
void creation.then(() => { this.agentCreation.delete(sessionId); }, () => { this.agentCreation.delete(sessionId); });
|
|
736
|
-
}
|
|
737
|
-
return creation;
|
|
738
|
-
}
|
|
739
|
-
/** 该会话是否属于「本 bot 服务的角色」的 c2c 导演会话(与 ensureAgent 判定一致)。 */
|
|
740
|
-
async isDirectorSession(sessionId) {
|
|
741
|
-
if (!this.deps.roleId || this.deps.persona?.loadRole === undefined)
|
|
742
|
-
return false;
|
|
743
|
-
const role = await this.deps.persona.loadRole(this.deps.roleId);
|
|
744
|
-
if (!role)
|
|
745
|
-
return false;
|
|
746
|
-
const openid = this.deps.persona.openidFromSessionId?.(sessionId);
|
|
747
|
-
return openid !== undefined && openid === role.binding.openid && Boolean(role.persona);
|
|
748
|
-
}
|
|
749
|
-
/**
|
|
750
|
-
* 确保导演会话的持久化记录 agentPreset='pygmalion-director':补记
|
|
751
|
-
* agent-preset/selected 事件。dsh 冷恢复(含核心 api-proxy 路径)经
|
|
752
|
-
* resolveSessionPreset 决定挂哪个 preset,header 无 agentPreset、日志无
|
|
753
|
-
* selected 事件时回退 standard 默认 composition → director_send 等工具缺失。
|
|
754
|
-
* 每进程每会话只补记一次。
|
|
755
|
-
*/
|
|
756
|
-
async recordDirectorPreset(sessionId, agent) {
|
|
757
|
-
if (agent === undefined || this.directorPresetRecorded.has(sessionId))
|
|
758
|
-
return;
|
|
759
|
-
if (!(await this.isDirectorSession(sessionId)))
|
|
760
|
-
return;
|
|
761
|
-
this.directorPresetRecorded.add(sessionId);
|
|
762
|
-
try {
|
|
763
|
-
agent.session.append('agent-preset/selected', { agentPreset: 'pygmalion-director' });
|
|
764
|
-
this.deps.log.info('QQ ensureAgent: 补记导演 preset 到 %s (agent-preset/selected)', sessionId);
|
|
765
|
-
}
|
|
766
|
-
catch (error) {
|
|
767
|
-
this.deps.log.warn('QQ ensureAgent: 补记导演 preset 失败 %s: %o', sessionId, error);
|
|
768
|
-
}
|
|
769
|
-
}
|
|
595
|
+
/** 兼容旧调用入口;模型、工作区和恢复交给角色会话服务。 */
|
|
596
|
+
async ensureAgent(sessionId) { return this.roleAgents.ensureAgent(sessionId); }
|
|
597
|
+
async isDirectorSession(sessionId) { return this.roleAgents.isDirectorSession(sessionId); }
|
|
598
|
+
async recordDirectorPreset(sessionId, agent) { return this.roleAgents.recordDirectorPreset(sessionId, agent); }
|
|
770
599
|
/** Record when this conversation last saw a real user message. */
|
|
771
600
|
markUserActivity(sessionId, at = Date.now()) {
|
|
772
601
|
this.lastActivity.set(sessionId, at);
|
|
@@ -777,7 +606,7 @@ export class InboundPipeline {
|
|
|
777
606
|
}
|
|
778
607
|
/** Forget in-flight creation state after an agent is disposed. */
|
|
779
608
|
onAgentDisposed(sessionId) {
|
|
780
|
-
this.agentCreation.delete(sessionId);
|
|
609
|
+
this.roleAgents.agentCreation.delete(sessionId);
|
|
781
610
|
this.stopTyping(sessionId);
|
|
782
611
|
}
|
|
783
612
|
/** Clear every typing timer; used during plugin teardown. */
|
|
@@ -814,4 +643,4 @@ export function botIdOfSession(sessionId) {
|
|
|
814
643
|
const parts = String(sessionId ?? '').split('#')[0].split(':');
|
|
815
644
|
return parts[1] === 'v2' && parts.length >= 3 ? parts[2] : undefined;
|
|
816
645
|
}
|
|
817
|
-
//# sourceMappingURL=inbound.js.map
|
|
646
|
+
//# sourceMappingURL=inbound.js.map
|
package/src/index.js
CHANGED
|
@@ -7,22 +7,26 @@
|
|
|
7
7
|
* 沉默归档/生活脚本/rewake 到期;全局唯一的管理网页经 botApi 读写机器人凭据。
|
|
8
8
|
*/
|
|
9
9
|
import { homedir } from 'node:os';
|
|
10
|
-
import { join } from 'node:path';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
10
|
+
import { join, resolve, dirname, basename } from 'node:path';
|
|
11
|
+
import { mkdir } from 'node:fs/promises';
|
|
12
|
+
import { createBotPipeline, connectionOfSession } from './bot-factory.js';
|
|
13
|
+
import { createQqAdapter } from './channel-qq.js';
|
|
14
14
|
import { createBotManager } from './bots.js';
|
|
15
15
|
import { createLogSink } from './log.js';
|
|
16
|
-
import { unarchiveOwnQQSessions } from './dsh-bookkeeping.js';
|
|
17
16
|
import { Config } from './config.js';
|
|
18
17
|
import { createHeartbeatScheduler } from './heartbeat.js';
|
|
19
18
|
import { createWebServer } from './web-server.js';
|
|
20
19
|
import { recoverLifeScripts } from './agent-life.js';
|
|
21
20
|
import { registerRoleProvider, unregisterRoleProvider, syncAllRoleProviders } from './llm-provider.js';
|
|
22
|
-
import { registerStandingTools } from './tools.js';
|
|
23
|
-
import { botIdOfSession } from './inbound.js';
|
|
21
|
+
import { registerStandingTools, CHAT_TOOL_NAMES } from './tools.js';
|
|
24
22
|
import { createDeviceManager } from './devices/manager.mjs';
|
|
23
|
+
import { createDeviceExtensionRegistry } from './devices/registry.mjs';
|
|
25
24
|
import * as personaLib from './persona.js';
|
|
25
|
+
import { createRoleplayService, registerRoleplayTools } from './roleplay-generation.js';
|
|
26
|
+
import { createRoleplaySessionBackend } from './roleplay-session.js';
|
|
27
|
+
import { createBundledVoiceServices } from './voice-defaults.js';
|
|
28
|
+
import { voiceCapabilityNotice } from './voice.js';
|
|
29
|
+
import { matchesRoleTarget } from './peer-identity.js';
|
|
26
30
|
|
|
27
31
|
// Re-export the schema so DSH can mount this plugin via `name: 'pygmalion'`.
|
|
28
32
|
export { Config };
|
|
@@ -61,24 +65,9 @@ function resolveOptionalServices(ctx, log) {
|
|
|
61
65
|
}
|
|
62
66
|
|
|
63
67
|
/**
|
|
64
|
-
*
|
|
65
|
-
* $DSH_HOME/.agent-presets/pygmalion-director/,并确保数据目录(accounts/roles)存在。
|
|
66
|
-
* 这样 `dsh plugin --profile web add <源>` 安装后无需任何手动操作即可使用。
|
|
68
|
+
* preset 随包声明,由宿主管理;只确保原位置的数据目录存在,不搬动历史数据。
|
|
67
69
|
*/
|
|
68
70
|
async function ensureInstalled(home, persona, log) {
|
|
69
|
-
try {
|
|
70
|
-
const presetSrc = fileURLToPath(new URL('../preset/pygmalion-director', import.meta.url));
|
|
71
|
-
const presetDst = join(home, '.agent-presets', 'pygmalion-director');
|
|
72
|
-
await mkdir(presetDst, { recursive: true });
|
|
73
|
-
await Promise.all([
|
|
74
|
-
copyFile(join(presetSrc, 'preset.yml'), join(presetDst, 'preset.yml')),
|
|
75
|
-
copyFile(join(presetSrc, 'agent.cordis.yml'), join(presetDst, 'agent.cordis.yml')),
|
|
76
|
-
copyFile(join(presetSrc, 'pygmalion-tools.js'), join(presetDst, 'pygmalion-tools.js')),
|
|
77
|
-
]);
|
|
78
|
-
log?.info?.('pygmalion: 导演 preset 已就位 %s', presetDst);
|
|
79
|
-
} catch (e) {
|
|
80
|
-
log?.warn?.('pygmalion: preset 自动安装失败 %o', e);
|
|
81
|
-
}
|
|
82
71
|
try {
|
|
83
72
|
for (const d of [persona.accountsDir(), persona.rolesDir(), persona.devicesDir()]) await mkdir(d, { recursive: true });
|
|
84
73
|
log?.info?.('pygmalion: 数据目录已就位 %s', persona.dataRoot());
|
|
@@ -96,12 +85,23 @@ export function apply(ctx, config) {
|
|
|
96
85
|
const workspaceRegistry = ctx.workspaceRegistry;
|
|
97
86
|
const { attachments, approval, agentPresets, webServer, settings, credentials } = resolveOptionalServices(ctx, log);
|
|
98
87
|
const persona = personaLib;
|
|
88
|
+
const { extensions, voice } = createBundledVoiceServices({ persona, extensions: createDeviceExtensionRegistry() });
|
|
89
|
+
ctx.provide('pygmalion.extensions', extensions);
|
|
90
|
+
ctx.effect(() => () => { voice.dispose(); extensions.dispose(); }, 'pygmalion.voice()');
|
|
91
|
+
const roleplayBackend = agentPresets ? createRoleplaySessionBackend({agents,agentPresets,persistence:sessionPersistence,sessions:ctx.get('sessions'),titles:ctx.get('sessionTitle',false)}) : undefined;
|
|
92
|
+
const roleplay = createRoleplayService({ persona, backend:roleplayBackend, log,
|
|
93
|
+
notifyReady:async (_roleId,parentId,batchId)=>{
|
|
94
|
+
const parent=agents.get(parentId);
|
|
95
|
+
parent?.followup({id:`roleplay-ready:${batchId}`,role:'user',source:{kind:'pygmalion-roleplay-delivery'},
|
|
96
|
+
content:[{type:'text',text:'[系统通知] 角色会话已有完整待交付消息。调用 roleplay_generate 获取,并将全部消息原样交给发送工具。'}]});
|
|
97
|
+
} });
|
|
98
|
+
ctx.on('session/event',(session,event)=>roleplay.observe(session,event));
|
|
99
|
+
ctx.effect(()=>()=>roleplay.dispose(),'pygmalion.roleplay()');
|
|
99
100
|
// 设备远控 DeviceManager:进程内持有每角色设备运行时(连接/计时/脚本/唤醒)。
|
|
100
|
-
const devices = createDeviceManager({ persona: personaLib, log });
|
|
101
|
-
//
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
void syncAllRoleProviders(ctx, persona, log);
|
|
101
|
+
const devices = createDeviceManager({ persona: personaLib, log, extensions });
|
|
102
|
+
// 启动就绪门:接入 QQ 前完成目录与角色模型注册;模型失败不会切到宿主默认模型。
|
|
103
|
+
const ready = ensureInstalled(home, persona, log).then(() => syncAllRoleProviders(ctx, persona, log));
|
|
104
|
+
void ready.catch(error => log.error('pygmalion: 初始化失败: %o', error));
|
|
105
105
|
// 供管理台保存/删除角色时注册/注销自定义 provider(settings/credentials 服务缺失时降级为 no-op)。
|
|
106
106
|
const llmProviders = {
|
|
107
107
|
register: (role) => registerRoleProvider(ctx, role, log),
|
|
@@ -138,7 +138,7 @@ export function apply(ctx, config) {
|
|
|
138
138
|
walkId = parent;
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
|
-
const builder = sessionBuilders.get(
|
|
141
|
+
const builder = sessionBuilders.get(connectionOfSession(sessionId));
|
|
142
142
|
if (builder === undefined)
|
|
143
143
|
return undefined;
|
|
144
144
|
try {
|
|
@@ -152,20 +152,76 @@ export function apply(ctx, config) {
|
|
|
152
152
|
return undefined;
|
|
153
153
|
}
|
|
154
154
|
};
|
|
155
|
+
const registeredScopes = new WeakSet();
|
|
155
156
|
let standingToolsRegistered = false;
|
|
156
157
|
ctx.provide('pygmalion.director', {
|
|
158
|
+
newParallelSession: request => roleplay.requestNew({...request,sessionPersistence}),
|
|
157
159
|
registerStandingTools(standCtx) {
|
|
158
|
-
if (
|
|
160
|
+
if (registeredScopes.has(standCtx))
|
|
159
161
|
return true;
|
|
160
|
-
const ok = registerStandingTools(standCtx, depsFor);
|
|
162
|
+
const ok = registerStandingTools(standCtx, depsFor, CHAT_TOOL_NAMES);
|
|
163
|
+
if (ok) registerRoleplayTools(standCtx, ctx.get('pygmalion.director'), roleplay);
|
|
161
164
|
standingToolsRegistered = standingToolsRegistered || ok;
|
|
165
|
+
if (ok) registeredScopes.add(standCtx);
|
|
162
166
|
return ok;
|
|
163
167
|
},
|
|
164
168
|
registerSession(sessionId, deps) { sessionDeps.set(sessionId, deps); },
|
|
165
169
|
registerSessionBuilder(botId, builder) { sessionBuilders.set(botId, builder); },
|
|
170
|
+
unregisterSessionBuilder(botId) { sessionBuilders.delete(botId); },
|
|
166
171
|
depsFor,
|
|
172
|
+
deviceSkillsForRole: role => devices.skillDefinitions(role),
|
|
173
|
+
onDeviceChange: listener => extensions.subscribe(listener),
|
|
174
|
+
registerDeviceTools(scope, driverId) {
|
|
175
|
+
return devices.registerTools(scope, driverId, async exec => {
|
|
176
|
+
if (!exec.agent || exec.agent.session.header.parentSession) throw new Error('设备操作仅供角色主会话使用');
|
|
177
|
+
const deps = await depsFor(exec.agent.id);
|
|
178
|
+
const role = deps?.roleId && await persona.loadRole(deps.roleId);
|
|
179
|
+
const target = deps?.target?.();
|
|
180
|
+
if (!matchesRoleTarget(role, target, deps.identityScope)) throw new Error('当前会话不是角色绑定的私人聊天');
|
|
181
|
+
return { roleId: role.roleId };
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
ready,
|
|
167
185
|
unregisterSession(sessionId) { sessionDeps.delete(sessionId); },
|
|
168
186
|
hasStandingTools() { return standingToolsRegistered; },
|
|
187
|
+
registerCapabilityTools(scope, names) {
|
|
188
|
+
const disposers = [];
|
|
189
|
+
registerStandingTools(scope, depsFor, names, disposers);
|
|
190
|
+
return async () => { for (const release of disposers) await release(); };
|
|
191
|
+
},
|
|
192
|
+
async roleForWorkspace(cwd) {
|
|
193
|
+
if (typeof cwd !== 'string' || !cwd) return undefined;
|
|
194
|
+
const normalize = value => {
|
|
195
|
+
const path = resolve(value).replaceAll('\\', '/').replace(/\/$/, '');
|
|
196
|
+
return process.platform === 'win32' ? path.toLowerCase() : path;
|
|
197
|
+
};
|
|
198
|
+
// 工作区沿用既有 roles/<roleId>/workspace;每轮只读取当前角色,避免扫描全部账号。
|
|
199
|
+
const roleId = basename(dirname(resolve(cwd)));
|
|
200
|
+
const expected = join(personaLib.rolesDir(), roleId, 'workspace');
|
|
201
|
+
if (normalize(expected) !== normalize(cwd)) return undefined;
|
|
202
|
+
const role = await personaLib.loadRole(roleId);
|
|
203
|
+
return role && normalize(role.workspace) === normalize(cwd) ? role : undefined;
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
208
|
+
const result = await next();
|
|
209
|
+
const header = context.agent?.session?.header;
|
|
210
|
+
if (!['pygmalion-director', 'pygmalion-roleplay-worker'].includes(header?.agentPreset)) return result;
|
|
211
|
+
const role = await ctx.get('pygmalion.director').roleForWorkspace(header.cwd);
|
|
212
|
+
if (!role) return result;
|
|
213
|
+
return { ...result, sections: [...result.sections, { name: 'pygmalion:voice-capabilities', order: 900,
|
|
214
|
+
text: voiceCapabilityNotice(await voice.view(role.roleId)), interpolate: false }] };
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// 主会话重新出现后只唤醒交付,不重跑已完成的角色生成;后台角色会话不进入此路径。
|
|
218
|
+
ctx.on('agent/created',({agent})=>{
|
|
219
|
+
if(agent.session.header.agentPreset!=='pygmalion-director'||!connectionOfSession(agent.id))return;
|
|
220
|
+
setTimeout(()=>{void (async()=>{
|
|
221
|
+
if(agents.get(agent.id)!==agent)return;
|
|
222
|
+
const role=await ctx.get('pygmalion.director').roleForWorkspace(agent.session.header.cwd);
|
|
223
|
+
if(role?.roleplay?.enabled)await roleplay.resumePending(role.roleId,agent);
|
|
224
|
+
})().catch(error=>log.warn('角色待交付消息恢复失败: %o',error));},0).unref?.();
|
|
169
225
|
});
|
|
170
226
|
|
|
171
227
|
// 每 bot 管线共享的宿主依赖;BotManager 建/重启管线时逐 bot 传入规范化记录。
|
|
@@ -174,39 +230,51 @@ export function apply(ctx, config) {
|
|
|
174
230
|
attachments, approval, agentPresets, webServer,
|
|
175
231
|
persona, log, storages, config,
|
|
176
232
|
devices,
|
|
233
|
+
voice, extensions,
|
|
177
234
|
director: ctx, // 供 bot-factory/setup-agent 经 ctx.get('pygmalion.director') 取服务
|
|
178
235
|
};
|
|
236
|
+
extensions.registerChannelAdapter(createQqAdapter(pipelineDeps, ctx));
|
|
179
237
|
const manager = createBotManager({
|
|
238
|
+
extensions, defaultAdapterId: 'qq-official',
|
|
180
239
|
config,
|
|
181
240
|
log,
|
|
182
241
|
persona,
|
|
183
242
|
buildPipeline: (record) => createBotPipeline(pipelineDeps, record, ctx),
|
|
184
243
|
});
|
|
185
244
|
|
|
245
|
+
ctx.effect(() => extensions.subscribe(() => { void manager.refreshAdapters().catch(error => log.warn('通信实现更新失败: %o', error)); }));
|
|
186
246
|
let heartbeat = null;
|
|
187
247
|
let web = null;
|
|
188
248
|
|
|
189
249
|
ctx.effect(() => {
|
|
250
|
+
let disposed = false;
|
|
190
251
|
// Best-effort unarchive runs first so the first inbound is not blocked
|
|
191
252
|
// by a synchronous file read on the plugin-loading thread.
|
|
192
|
-
|
|
193
|
-
|
|
253
|
+
// 尊重用户归档状态;不再直接改写宿主 workspace.json。
|
|
254
|
+
if (config.maintenanceMode) {
|
|
255
|
+
log.info('pygmalion: 维护模式,外部交互和脚本恢复均未启动');
|
|
256
|
+
return () => { void devices.disposeAll(); };
|
|
257
|
+
}
|
|
194
258
|
|
|
195
259
|
// 跨重启内存级恢复:dsh 上次运行期间仍在跑的生活脚本(detached 已存活,或随 dsh 一起退出),
|
|
196
260
|
// 重启后立即按 life/.running.json 重新登记/重新拉起,无需等 heartbeat 首个 tick。
|
|
197
261
|
// 遍历所有角色而非管线:恢复只依赖 workspace 下的 .running.json,与 pipeline 就绪与否无关。
|
|
198
|
-
void (async () => {
|
|
262
|
+
void ready.then(async () => {
|
|
263
|
+
if (disposed) return;
|
|
264
|
+
await manager.startAll();
|
|
199
265
|
try {
|
|
200
266
|
for (const role of await personaLib.listRoles()) {
|
|
267
|
+
if (disposed) return;
|
|
268
|
+
if (manager.recordForRole(role.roleId)?.enabled === false) continue;
|
|
201
269
|
await recoverLifeScripts(role.workspace)
|
|
202
270
|
.catch((e) => log.warn?.('pygmalion 启动恢复生活脚本失败 %s: %o', role.roleId, e));
|
|
203
271
|
}
|
|
204
272
|
}
|
|
205
273
|
catch (e) { log.warn?.('pygmalion 启动恢复生活脚本失败: %o', e); }
|
|
206
|
-
})();
|
|
274
|
+
}).catch((e) => log.error('pygmalion 启动恢复失败: %o', e));
|
|
207
275
|
|
|
208
276
|
// 全局唯一心跳:每次 tick 现取管线列表(网页动态增删 bot 即时生效)。
|
|
209
|
-
heartbeat = createHeartbeatScheduler({ config, log, persona, pipelines: () => manager.getPipelines(), subagents: ctx.get('subagents'), llm: ctx.get('llm') });
|
|
277
|
+
heartbeat = createHeartbeatScheduler({ config, log, persona, sessionPersistence, pipelines: () => manager.getPipelines(), subagents: ctx.get('subagents'), llm: ctx.get('llm') });
|
|
210
278
|
heartbeat.start();
|
|
211
279
|
|
|
212
280
|
// 全局唯一管理网页(登录鉴权 + 多角色管理 + 机器人凭据 + 脚本监管)。
|
|
@@ -215,7 +283,10 @@ export function apply(ctx, config) {
|
|
|
215
283
|
log,
|
|
216
284
|
web: config.web,
|
|
217
285
|
llmProviders,
|
|
286
|
+
beforeRoleDelete: (roleId) => roleplay.deleteRole(roleId),
|
|
287
|
+
afterRoleDelete: (roleId) => roleplay.finishDelete(roleId),
|
|
218
288
|
devices,
|
|
289
|
+
voice, extensions,
|
|
219
290
|
botApi: {
|
|
220
291
|
list: () => manager.getBots(),
|
|
221
292
|
upsertForRole: (roleId, input) => manager.upsertForRole(roleId, input),
|
|
@@ -227,9 +298,10 @@ export function apply(ctx, config) {
|
|
|
227
298
|
void web.start().catch((e) => log.error('pygmalion web 启动失败: %o', e));
|
|
228
299
|
|
|
229
300
|
return () => {
|
|
301
|
+
disposed = true;
|
|
230
302
|
try { heartbeat?.stop(); } catch { /* ignore */ }
|
|
231
303
|
try { manager.stopAll(); } catch { /* ignore */ }
|
|
232
|
-
try { void devices.
|
|
304
|
+
try { void devices.disposeAll(); } catch { /* ignore */ }
|
|
233
305
|
void web?.stop().catch(() => { /* ignore */ });
|
|
234
306
|
};
|
|
235
307
|
}, 'pygmalion.gateway()');
|