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
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** 归档工作会话:只加载记忆工作流与文件工具,不挂角色发送与设备能力。 */
|
|
2
|
+
import { registerPygmalionSkills } from './skills.js';
|
|
3
|
+
import { restrictWorkerTools } from './worker-tools.js';
|
|
4
|
+
export const name = 'pygmalion-archive-tools';
|
|
5
|
+
export const inject = ['tools', 'skills', 'pygmalion.director'];
|
|
6
|
+
export function apply(ctx) {
|
|
7
|
+
registerPygmalionSkills(ctx, ctx.get('pygmalion.director'), 'archive');
|
|
8
|
+
restrictWorkerTools(ctx, ['read', 'write', 'edit', 'glob', 'grep', 'pwsh', 'bash', 'skill']);
|
|
9
|
+
}
|
package/src/bot-factory.js
CHANGED
|
@@ -1,319 +1,137 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 单 bot 管线工厂:把一个 bot 记录(data/bots/<id>.json)构建成完整接入管线。
|
|
3
|
-
*
|
|
4
|
-
* 由 BotManager 在启动/运行时调用:start() 内包一个 `ctx.effect`(活跃 fiber 内注册
|
|
5
|
-
* `ctx.on('agent/disposed')` 与 dsh `webServer.register`,effect teardown 即注销),
|
|
6
|
-
* stop() 就是该 effect 返回的 disposer。store 文件名按 botId 隔离(qq-<botId>-*.json)。
|
|
7
|
-
*/
|
|
1
|
+
/** 通信管线接线:角色服务复用,协议实现通过注册表提供。保留旧导出名。 */
|
|
8
2
|
import { join } from 'node:path';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { RefIndexStore } from './refindex.js';
|
|
12
|
-
import { AlwaysAllowStore, RouteStore } from './store.js';
|
|
13
|
-
import { InboundPipeline, normalizeMessage, SESSION_PREFIX, effectiveSessionId } from './inbound.js';
|
|
14
|
-
import { OutboundPipeline } from './outbound.js';
|
|
15
|
-
import { createSlashHandler } from './slash-commands.js';
|
|
16
|
-
import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { RouteStore } from './store.js';
|
|
17
5
|
import { ThreadStore, targetKey } from './threads.js';
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import
|
|
6
|
+
import { createRoleRuntime } from './role-runtime.js';
|
|
7
|
+
import { registerRoleProvider } from './llm-provider.js';
|
|
8
|
+
import { bindingStamp, matchesRoleTarget } from './peer-identity.js';
|
|
9
|
+
import { refreshRawRecordFromSession } from './memory-write.js';
|
|
10
|
+
import { createHttpApiHandler } from './http-api.js';
|
|
21
11
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
if (payload === null || typeof payload !== 'object')
|
|
27
|
-
return undefined;
|
|
28
|
-
const root = payload;
|
|
29
|
-
if (typeof root.id !== 'string')
|
|
30
|
-
return undefined;
|
|
31
|
-
const data = root.data;
|
|
32
|
-
if (data === null || typeof data !== 'object')
|
|
33
|
-
return undefined;
|
|
34
|
-
const resolved = data.resolved;
|
|
35
|
-
if (resolved === null || typeof resolved !== 'object')
|
|
36
|
-
return undefined;
|
|
37
|
-
const buttonData = resolved.button_data;
|
|
38
|
-
if (typeof buttonData !== 'string')
|
|
39
|
-
return undefined;
|
|
40
|
-
return { id: root.id, buttonData };
|
|
12
|
+
export function connectionOfSession(id) {
|
|
13
|
+
const parts=String(id).split('#')[0].split(':');
|
|
14
|
+
if(parts[0]==='pygmalion'&&parts[1]==='v1')return parts[2];
|
|
15
|
+
if(parts[0]==='qq'&&parts[1]==='v2'&&parts.length>=5)return parts[2];
|
|
41
16
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
});
|
|
97
|
-
const presetOverride = (typeof bot.agentPreset === 'string' && bot.agentPreset.length > 0)
|
|
98
|
-
? bot.agentPreset
|
|
99
|
-
: 'standard';
|
|
100
|
-
const setupDeps = {
|
|
101
|
-
log,
|
|
102
|
-
api,
|
|
103
|
-
routes,
|
|
104
|
-
outbound,
|
|
105
|
-
workspaceRegistry: deps.workspaceRegistry,
|
|
106
|
-
persona,
|
|
107
|
-
roleId: bot.roleId,
|
|
108
|
-
devices: deps.devices,
|
|
109
|
-
subagents: ctx.get('subagents'),
|
|
110
|
-
llm: ctx.get('llm'),
|
|
111
|
-
defaultCwd: process.cwd(),
|
|
112
|
-
resolvePreset: deps.agentPresets === undefined
|
|
113
|
-
? undefined
|
|
114
|
-
: async (sessionId) => {
|
|
115
|
-
let presetId = presetOverride;
|
|
116
|
-
const openid = persona.openidFromSessionId(sessionId);
|
|
117
|
-
if (openid !== undefined) {
|
|
118
|
-
try {
|
|
119
|
-
const role = await persona.loadRole(bot.roleId);
|
|
120
|
-
if (role && role.binding.openid === openid && role.persona?.name) {
|
|
121
|
-
presetId = 'pygmalion-director';
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
catch (error) {
|
|
125
|
-
log.warn('pygmalion loadRole failed for %s: %o', openid, error);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
return deps.agentPresets.resolve(threads.presetFor(sessionId) ?? presetId);
|
|
129
|
-
},
|
|
130
|
-
agentPresets: deps.agentPresets,
|
|
131
|
-
httpApiToken: bot.httpApiToken,
|
|
132
|
-
httpApiPath: bot.httpApiPath,
|
|
133
|
-
director: deps.director,
|
|
134
|
-
};
|
|
135
|
-
const setupAgent = createSetupAgent(setupDeps);
|
|
136
|
-
// 已存在 agent(dsh 核心冷恢复/重组合创建,未走 pygmalion setup)时,ensureAgent
|
|
137
|
-
// 命中既有分支不会执行 setup → standing 导演工具缺会话上下文。此回调只补登记
|
|
138
|
-
// sessionDeps(不重挂 preset——mount 对已绑定 agent 会 throw),幂等可重复调用。
|
|
139
|
-
const registerSessionContext = (sessionId) => {
|
|
140
|
-
const directorSvc = deps.director?.get?.('pygmalion.director');
|
|
141
|
-
if (directorSvc === undefined || typeof directorSvc.registerSession !== 'function') return;
|
|
142
|
-
directorSvc.registerSession(sessionId, buildSessionDeps(setupDeps, sessionId));
|
|
143
|
-
};
|
|
144
|
-
// 冷恢复兜底(修 D19):重启后 dsh 核心重建既有 agent 不触发 setup/ensureAgent(无入站
|
|
145
|
-
// 消息),sessionDeps 永不登记。向宿主登记惰性构造器,depsFor 未命中时按 sessionId
|
|
146
|
-
// 现场构造并缓存(buildSessionDeps 除 target 惰性闭包外全是本 bot 常量,任意会话可构造)。
|
|
147
|
-
const directorSvc = deps.director?.get?.('pygmalion.director');
|
|
148
|
-
if (directorSvc !== undefined && typeof directorSvc.registerSessionBuilder === 'function') {
|
|
149
|
-
directorSvc.registerSessionBuilder(bot.id, (sessionId) => buildSessionDeps(setupDeps, sessionId));
|
|
17
|
+
export function createBotPipeline(deps, record, ctx) {
|
|
18
|
+
const entry=deps.extensions.getChannelAdapter(record.adapterId);
|
|
19
|
+
const descriptor=entry?.descriptor;
|
|
20
|
+
const lifetime=new AbortController();
|
|
21
|
+
const ns=descriptor?.storageNamespace?.(record.id) ?? `channel-${record.id}`;
|
|
22
|
+
const routes=new RouteStore(join(deps.storages,`${ns}-routes.json`));
|
|
23
|
+
const threads=new ThreadStore(join(deps.storages,`${ns}-threads.json`));
|
|
24
|
+
const seen=new Set(),activity=new Map();
|
|
25
|
+
let runtime,port,api,status={state:'stopped',detail:''},started=false,closed=false,unmount;
|
|
26
|
+
const signal=entry?AbortSignal.any([entry.signal,lifetime.signal]):lifetime.signal;
|
|
27
|
+
let identityScope;
|
|
28
|
+
const targetForPeer=peerId=>port?.targetForPeer?.(peerId) ?? {kind:'direct',identity:{...identityScope,peerId}};
|
|
29
|
+
const sessionIdFor=target=>{
|
|
30
|
+
const id=port?.sessionIdFor?.(target) ?? `pygmalion:v1:${record.id}:${createHash('sha256').update(targetKey(target)).digest('hex')}#dsh021#n${threads.current(targetKey(target))}`;
|
|
31
|
+
routes.ensure(id,target);return id;
|
|
32
|
+
};
|
|
33
|
+
const targetForSession=id=>routes.get(id)?.target ?? port?.targetForSession?.(id);
|
|
34
|
+
const boundTarget=async(role=undefined)=>{
|
|
35
|
+
role??=await deps.persona.loadRole(record.roleId);
|
|
36
|
+
const peer=role?.binding?.peer;
|
|
37
|
+
const target=peer?targetForPeer(peer.peerId):role?.binding?.openid?targetForPeer(role.binding.openid):undefined;
|
|
38
|
+
return matchesRoleTarget(role,target,identityScope)?target:undefined;
|
|
39
|
+
};
|
|
40
|
+
async function accept(event) {
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
if(!event||event.isSelf||event.replayed||event.kind&&event.kind!=='direct'||typeof event.peerId!=='string'||!event.peerId)return;
|
|
43
|
+
if(typeof event.id!=='string'||!event.id)throw new Error('入站消息必须提供稳定 ID');
|
|
44
|
+
if(seen.has(event.id))return;seen.add(event.id);if(seen.size>2000)seen.delete(seen.values().next().value);
|
|
45
|
+
const bind=await deps.persona.bindRoleIdentity(record.roleId,{...identityScope,peerId:event.peerId},{allowNewBinding:true});
|
|
46
|
+
if(!['bound','already'].includes(bind.status))return bind;
|
|
47
|
+
const target=targetForPeer(event.peerId),sessionId=sessionIdFor(target),stamp=bindingStamp(bind.role);
|
|
48
|
+
return {...bind,target,sessionId,async deliver(content,sentAt) {
|
|
49
|
+
signal.throwIfAborted();
|
|
50
|
+
const current=await deps.persona.loadRole(record.roleId);
|
|
51
|
+
if(bindingStamp(current)!==stamp)throw new Error('角色绑定已改变,入站处理已取消');
|
|
52
|
+
const at=Number.isFinite(sentAt)?sentAt:Date.now();activity.set(sessionId,at);
|
|
53
|
+
if(routes.get(sessionId)?.lastMsgId!==event.id)routes.anchor(sessionId,target,event.id);
|
|
54
|
+
const agent=await runtime.roleAgents.ensureAgent(sessionId);
|
|
55
|
+
signal.throwIfAborted();
|
|
56
|
+
if(bindingStamp(await deps.persona.loadRole(record.roleId))!==stamp)throw new Error('角色绑定已改变');
|
|
57
|
+
await agent.send({id:event.id,role:'user',content,
|
|
58
|
+
source:{kind:'user',rpcId:`pygmalion.inbound:${record.id}:${event.id}`,...(Number.isFinite(sentAt)?{sentAt}:{})}},'next-turn',true);
|
|
59
|
+
// 从日志提取原文仍使用既有机制,通信实现不写第二份聊天记录。
|
|
60
|
+
setTimeout(()=>{if(!signal.aborted)void refreshRawRecordFromSession({workspace:current.workspace,sessionId,
|
|
61
|
+
persistence:deps.sessionPersistence,charLabel:current.persona?.name??record.roleId,log:deps.log}).catch(error=>deps.log?.warn?.('原文提取失败: %o',error));},3000).unref?.();
|
|
62
|
+
}};
|
|
63
|
+
}
|
|
64
|
+
async function receive(event) {
|
|
65
|
+
const accepted=await accept(event);if(!accepted||!['bound','already'].includes(accepted.status))return;
|
|
66
|
+
if(typeof event.text!=='string')throw new Error('入站 text 必须为字符串');
|
|
67
|
+
const text=event.text;
|
|
68
|
+
if(text==='/new') {
|
|
69
|
+
deps.agents.get(accepted.sessionId)?.cancel({kind:'user'});threads.next(targetKey(accepted.target));
|
|
70
|
+
await api.sendText(accepted.target,'【系统提示】已开启新会话,历史记忆保留。');return;
|
|
150
71
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
let httpApiMount;
|
|
156
|
-
let httpApiUnavailable = false;
|
|
157
|
-
if (bot.httpApiToken) {
|
|
158
|
-
httpApiMount = resolveHttpApiMount({ path: bot.httpApiPath, token: bot.httpApiToken });
|
|
159
|
-
if (deps.webServer === undefined) {
|
|
160
|
-
httpApiMount = undefined;
|
|
161
|
-
httpApiUnavailable = true;
|
|
162
|
-
log.warn('pygmalion: bot %s 配置了 httpApiToken,但宿主无 webServer(该 API 仅在 dsh web 等 Web 组合下可用),已跳过挂载', bot.id);
|
|
163
|
-
}
|
|
72
|
+
if(text==='/newp') {
|
|
73
|
+
const result=await deps.director?.get?.('pygmalion.director')?.newParallelSession?.({roleId:record.roleId,
|
|
74
|
+
userId:event.peerId,target:accepted.target,identityScope,sessionPersistence:deps.sessionPersistence});
|
|
75
|
+
await api.sendText(accepted.target,result?.status==='ready'?'【系统提示】已新建角色平行会话。':'【系统提示】当前角色回复仍在处理或角色会话不可用。');return;
|
|
164
76
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
});
|
|
177
|
-
},
|
|
178
|
-
onInteraction: (payload) => {
|
|
179
|
-
const interaction = asInteractionButton(payload);
|
|
180
|
-
if (interaction === undefined)
|
|
181
|
-
return;
|
|
182
|
-
if (outbound.handleApprovalCallback(interaction.buttonData) !== undefined) {
|
|
183
|
-
void api.ackInteraction(interaction.id).catch((error) => {
|
|
184
|
-
log.warn('interaction ack failed: %o', error);
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
},
|
|
188
|
-
onReady: () => { log.info('QQ gateway ready (bot=%s appid=%s)', bot.id, api.appId()); },
|
|
189
|
-
onStatus: setStatus,
|
|
190
|
-
}, log, join(deps.storages, `${ns}-gateway-session.json`));
|
|
191
|
-
|
|
192
|
-
const facade = {
|
|
193
|
-
botId: bot.id,
|
|
194
|
-
roleId: bot.roleId,
|
|
195
|
-
routes,
|
|
196
|
-
threads,
|
|
197
|
-
inbound,
|
|
198
|
-
withinChatWindowMs: bot.withinChatWindowMs,
|
|
199
|
-
httpApiToken: bot.httpApiToken,
|
|
200
|
-
};
|
|
201
|
-
|
|
202
|
-
let dispose = null;
|
|
203
|
-
let started = false;
|
|
204
|
-
let stopping = false;
|
|
205
|
-
|
|
206
|
-
function start() {
|
|
207
|
-
if (started || stopping)
|
|
208
|
-
return;
|
|
209
|
-
started = true;
|
|
210
|
-
// ctx.effect 返回 disposer;effect 运行时 fiber 活跃,ctx.on / webServer.register 均合法。
|
|
211
|
-
dispose = ctx.effect(() => {
|
|
212
|
-
const stops = [];
|
|
213
|
-
void refIndex.init();
|
|
214
|
-
void routes.load().then(() => {
|
|
215
|
-
try {
|
|
216
|
-
routes.prune(ROUTE_TTL);
|
|
217
|
-
alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
|
|
218
|
-
}
|
|
219
|
-
catch { /* ignore */ }
|
|
220
|
-
});
|
|
221
|
-
void alwaysAllow.load();
|
|
222
|
-
void threads.load();
|
|
223
|
-
void gateway.start();
|
|
224
|
-
const pruneTimer = setInterval(() => {
|
|
225
|
-
try {
|
|
226
|
-
routes.prune(ROUTE_TTL);
|
|
227
|
-
alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
|
|
228
|
-
}
|
|
229
|
-
catch { /* ignore */ }
|
|
230
|
-
}, 6 * 3600 * 1000);
|
|
231
|
-
pruneTimer.unref?.();
|
|
232
|
-
stops.push(() => clearInterval(pruneTimer));
|
|
233
|
-
const onDisposed = ctx.on('agent/disposed', ({ agent }) => {
|
|
234
|
-
if (!agent.id.startsWith(`${SESSION_PREFIX}:${bot.id}:`))
|
|
235
|
-
return;
|
|
236
|
-
deps.director?.get?.('pygmalion.director')?.unregisterSession?.(agent.id);
|
|
237
|
-
void outbound.closeStream(agent.id);
|
|
238
|
-
inbound.onAgentDisposed(agent.id);
|
|
239
|
-
});
|
|
240
|
-
stops.push(() => { if (typeof onDisposed === 'function') onDisposed(); });
|
|
241
|
-
if (httpApiMount !== undefined && deps.webServer !== undefined) {
|
|
242
|
-
stops.push(deps.webServer.register({
|
|
243
|
-
kind: 'prefix',
|
|
244
|
-
path: httpApiMount.path,
|
|
245
|
-
handler: createHttpApiHandler({
|
|
246
|
-
mountPath: httpApiMount.path,
|
|
247
|
-
token: httpApiMount.token,
|
|
248
|
-
config: bot,
|
|
249
|
-
log,
|
|
250
|
-
api,
|
|
251
|
-
routes,
|
|
252
|
-
threads,
|
|
253
|
-
ensureAgent: (sessionId) => inbound.ensureAgent(sessionId),
|
|
254
|
-
persona,
|
|
255
|
-
devices: deps.devices,
|
|
256
|
-
botId: bot.id,
|
|
257
|
-
roleId: bot.roleId,
|
|
258
|
-
activityAt: (sessionId) => inbound.userActivityAt(sessionId),
|
|
259
|
-
withinChatWindowMs: bot.withinChatWindowMs,
|
|
260
|
-
scriptWakeMinIntervalMs: config?.heartbeat?.scriptWakeMinIntervalMs ?? 600000,
|
|
261
|
-
}),
|
|
262
|
-
}));
|
|
263
|
-
log.info('pygmalion: httpApi mounted for bot %s at %s', bot.id, httpApiMount.path);
|
|
264
|
-
}
|
|
265
|
-
// 普通设备事件遵守聊天撞车检测;脚本生命周期结束是高优先级内部信号,
|
|
266
|
-
// 可抢占正在 TTS/director_send 的调用,保证结束提醒进入导演下一轮。
|
|
267
|
-
if (deps.devices && typeof deps.devices.registerRole === 'function') {
|
|
268
|
-
const deviceWake = async (contextText, { priority = false } = {}) => {
|
|
269
|
-
try {
|
|
270
|
-
const role = await persona.loadRole(bot.roleId);
|
|
271
|
-
const openid = role?.binding?.openid;
|
|
272
|
-
if (!openid) return { ok: false, error: 'no-openid' };
|
|
273
|
-
const target = { kind: 'c2c', userId: openid };
|
|
274
|
-
const thread = threads.current(targetKey(target));
|
|
275
|
-
const sessionId = effectiveSessionId(target, thread, bot.id);
|
|
276
|
-
return await wakeupSession({
|
|
277
|
-
log, threads, persona, roleId: bot.roleId, botId: bot.id, routes,
|
|
278
|
-
ensureAgent: (sid) => inbound.ensureAgent(sid),
|
|
279
|
-
activityAt: (sid) => inbound.userActivityAt(sid),
|
|
280
|
-
withinChatWindowMs: bot.withinChatWindowMs,
|
|
281
|
-
}, {
|
|
282
|
-
target, reason: '设备事件', contextText,
|
|
283
|
-
force: priority,
|
|
284
|
-
interruptTool: priority ? 'director_send' : undefined,
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
catch (e) {
|
|
288
|
-
log.warn?.('device wake failed %s: %o', bot.roleId, e);
|
|
289
|
-
return { ok: false, error: String(e) };
|
|
290
|
-
}
|
|
291
|
-
};
|
|
292
|
-
deps.devices.registerRole(bot.roleId, deviceWake);
|
|
293
|
-
stops.push(() => deps.devices.unregisterRole?.(bot.roleId));
|
|
294
|
-
}
|
|
295
|
-
return () => {
|
|
296
|
-
stops.forEach((fn) => { try { fn(); } catch { /* ignore */ } });
|
|
297
|
-
outbound.disposeAllStreams();
|
|
298
|
-
inbound.dispose();
|
|
299
|
-
gateway.dispose();
|
|
300
|
-
api.dispose();
|
|
301
|
-
void outbound.dispose();
|
|
302
|
-
started = false;
|
|
303
|
-
dispose = null;
|
|
304
|
-
setStatus('stopped');
|
|
305
|
-
};
|
|
306
|
-
}, `pygmalion.bot:${bot.id}()`);
|
|
307
|
-
return dispose;
|
|
77
|
+
const content=[];
|
|
78
|
+
if(text)content.push({type:'text',text});
|
|
79
|
+
// 协议鉴权/取件属于实现;统一端仅接收明确的字节或受作用域限制的读取函数。
|
|
80
|
+
for(const attachment of event.attachments??[]) {
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
const data=attachment.data??await attachment.read?.({signal});
|
|
83
|
+
if(!(data instanceof Uint8Array)||data.byteLength>20*1024*1024)throw new Error('入站附件缺少有效字节或超过 20MB');
|
|
84
|
+
if(!['image/png','image/jpeg','image/gif','image/webp'].includes(attachment.mediaType))throw new Error('此通信实现的附件尚不支持当前媒体类型');
|
|
85
|
+
if(!deps.attachments)throw new Error('宿主图片服务不可用');
|
|
86
|
+
const image=await deps.attachments.saveImage({data,mediaType:attachment.mediaType,name:attachment.name??'image'});
|
|
87
|
+
content.push({type:'image',attachment:image});
|
|
308
88
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
|
|
89
|
+
if(content.length)await accepted.deliver(content,event.sentAt);
|
|
90
|
+
}
|
|
91
|
+
const host={routes,threads,accept,
|
|
92
|
+
roleAgents:{ensureAgent:id=>runtime.roleAgents.ensureAgent(id),isDirectorSession:id=>runtime.roleAgents.isDirectorSession(id),recordDirectorPreset:(...args)=>runtime.roleAgents.recordDirectorPreset(...args),get agentCreation(){return runtime.roleAgents.agentCreation;}},
|
|
93
|
+
setupAgent:(...args)=>runtime.setupAgent(...args),registerSessionContext:id=>runtime.registerSessionContext(id)};
|
|
94
|
+
const facade={botId:record.id,roleId:record.roleId,routes,threads,boundTarget,sessionIdFor,
|
|
95
|
+
withinChatWindowMs:record.withinChatWindowMs,httpApiToken:record.httpApiToken,
|
|
96
|
+
inbound:{ensureAgent:id=>runtime.roleAgents.ensureAgent(id),userActivityAt:id=>port?.inbound?.userActivityAt(id)??activity.get(id)},
|
|
97
|
+
wake:params=>runtime.wake(params)};
|
|
98
|
+
async function start() {
|
|
99
|
+
if(closed)throw new Error('连接已关闭');if(started)return; if(!entry)throw new Error('通信适配器不可用,配置已保留');
|
|
100
|
+
started=true;await Promise.all([routes.load(),threads.load()]);signal.throwIfAborted();
|
|
101
|
+
identityScope={adapterId:descriptor.id,accountId:descriptor.accountId(record.config)};
|
|
102
|
+
if(typeof identityScope.accountId!=='string'||!identityScope.accountId)throw new Error('通信账号作用域无效');
|
|
103
|
+
try {
|
|
104
|
+
const context=Object.fromEntries(['id','roleId','httpApiPath','httpApiToken','withinChatWindowMs','agentPreset'].map(key=>[key,record[key]]));
|
|
105
|
+
port=await descriptor.create({record:context,connectionId:record.id,roleId:record.roleId,config:record.config,signal,receive,
|
|
106
|
+
onStatus:(state,detail='')=>{status={state,detail};},host});
|
|
107
|
+
if(signal.aborted){await port.dispose?.();port=undefined;signal.throwIfAborted();}
|
|
108
|
+
const rawApi=port.api??port;
|
|
109
|
+
if(typeof rawApi.sendText!=='function')throw new Error('通信实现缺少 sendText');
|
|
110
|
+
api=new Proxy(rawApi,{get(object,key){
|
|
111
|
+
if(key==='supportsMedia')return type=>port.mediaTypes?.includes(type)===true;
|
|
112
|
+
if(!['sendText','sendMedia'].includes(key))return typeof object[key]==='function'?object[key].bind(object):object[key];
|
|
113
|
+
return async(target,...args)=>{signal.throwIfAborted();const guard=await runtime.beginDelivery(target);await guard.assertCurrent();
|
|
114
|
+
if(key==='sendMedia'&&!port.mediaTypes?.includes(args[0]))throw new Error('当前通信实现不支持此媒体类型');
|
|
115
|
+
if(typeof object[key]!=='function')throw new Error('当前通信实现没有此发送能力');return object[key](target,...args);};
|
|
116
|
+
}});
|
|
117
|
+
runtime=createRoleRuntime({...deps,subagents:ctx.get('subagents'),llm:ctx.get('llm'),prepareRoleProvider:role=>registerRoleProvider(ctx,role,deps.log)},record,
|
|
118
|
+
{api,routes,threads,outbound:port.outbound??{registerApprovalAnswerer(){}},identityScope,targetForSession,
|
|
119
|
+
targetForRole:boundTarget,sessionIdFor,activityAt:facade.inbound.userActivityAt});
|
|
120
|
+
runtime.start();
|
|
121
|
+
await port.start?.();signal.throwIfAborted();
|
|
122
|
+
if(!port.httpApiUnavailable&&deps.webServer&&!descriptor.ownsHttpApi)unmount=deps.webServer.register({kind:'prefix',path:record.httpApiPath,
|
|
123
|
+
handler:createHttpApiHandler({...deps,config:record,api,routes,threads,botId:record.id,roleId:record.roleId,mountPath:record.httpApiPath,
|
|
124
|
+
token:record.httpApiToken,ensureAgent:facade.inbound.ensureAgent,sessionIdFor,boundTarget,activityAt:facade.inbound.userActivityAt})});
|
|
125
|
+
signal.addEventListener('abort',stop,{once:true});
|
|
126
|
+
if(status.state==='stopped')status={state:'ready',detail:''};
|
|
127
|
+
}catch(error){stop();throw error;}
|
|
128
|
+
}
|
|
129
|
+
function stop(){
|
|
130
|
+
if(closed)return;closed=true;
|
|
131
|
+
lifetime.abort(new Error('通信连接已停止'));signal.removeEventListener('abort',stop);
|
|
132
|
+
runtime?.dispose();unmount?.();unmount=undefined;
|
|
133
|
+
if(port){const current=port;port=undefined;void Promise.resolve().then(()=>current.dispose?.()).catch(error=>deps.log?.warn?.('通信资源释放失败: %o',error));}
|
|
134
|
+
status={state:'stopped',detail:''};
|
|
135
|
+
}
|
|
136
|
+
return {bot:record,facade,adapterEntry:entry,start,stop,getStatus:()=>port?.getStatus?.()??status,get httpApiUnavailable(){return !deps.webServer||port?.httpApiUnavailable===true;}};
|
|
319
137
|
}
|