pygmalion 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,282 @@
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
+ */
8
+ import { join } from 'node:path';
9
+ import { QQApi } from './qqapi.js';
10
+ import { QQGateway } from './gateway.js';
11
+ import { RefIndexStore } from './refindex.js';
12
+ import { AlwaysAllowStore, RouteStore } from './store.js';
13
+ import { InboundPipeline, normalizeMessage, SESSION_PREFIX } from './inbound.js';
14
+ import { OutboundPipeline } from './outbound.js';
15
+ import { createSlashHandler } from './slash-commands.js';
16
+ import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
17
+ import { ThreadStore } from './threads.js';
18
+ import { resolveHttpApiMount, createHttpApiHandler } from './http-api.js';
19
+ import * as personaLib from './persona.js';
20
+
21
+ const ROUTE_TTL = 7 * 24 * 3600 * 1000; // 7 天无用户活动的会话路由修剪(修 D12)
22
+
23
+ /** Strict, narrow validator for QQ INTERACTION_CREATE payloads. */
24
+ function asInteractionButton(payload) {
25
+ if (payload === null || typeof payload !== 'object')
26
+ return undefined;
27
+ const root = payload;
28
+ if (typeof root.id !== 'string')
29
+ return undefined;
30
+ const data = root.data;
31
+ if (data === null || typeof data !== 'object')
32
+ return undefined;
33
+ const resolved = data.resolved;
34
+ if (resolved === null || typeof resolved !== 'object')
35
+ return undefined;
36
+ const buttonData = resolved.button_data;
37
+ if (typeof buttonData !== 'string')
38
+ return undefined;
39
+ return { id: root.id, buttonData };
40
+ }
41
+
42
+ /**
43
+ * @param deps 全局依赖(index.js apply 解析):
44
+ * agents / sessionPersistence / workspaceRegistry / attachments / approval /
45
+ * agentPresets / webServer(均来自 ctx)/ persona / log / storages(目录)
46
+ * @param bot bot 记录(已过 BotConfig schema 校验)
47
+ * @param ctx 宿主 context(注册/注销 agent 生命周期监听)
48
+ * @returns {
49
+ * bot, facade, // facade 供 heartbeat:{ botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
50
+ * getStatus(), // 最近一次 gateway 连接状态
51
+ * start(), stop() // 启动/停管线(幂等)
52
+ * }
53
+ */
54
+ export function createBotPipeline(deps, bot, ctx) {
55
+ const { log, persona, config } = deps;
56
+ const ns = `qq-${bot.id}`;
57
+ const api = new QQApi(bot, log);
58
+ const refIndex = new RefIndexStore(join(deps.storages, `${ns}-refindex.jsonl`));
59
+ const routes = new RouteStore(join(deps.storages, `${ns}-routes.json`));
60
+ const alwaysAllow = new AlwaysAllowStore(join(deps.storages, `${ns}-always-allow.json`));
61
+ const threads = new ThreadStore(join(deps.storages, `${ns}-threads.json`));
62
+ const inbound = new InboundPipeline({
63
+ config: bot,
64
+ api,
65
+ log,
66
+ refIndex,
67
+ routes,
68
+ agents: deps.agents,
69
+ sessionPersistence: deps.sessionPersistence,
70
+ attachments: deps.attachments,
71
+ approval: deps.approval,
72
+ threads,
73
+ persona,
74
+ roleId: bot.roleId,
75
+ botId: bot.id,
76
+ botAppId: bot.qqAppId,
77
+ });
78
+ const outbound = new OutboundPipeline({
79
+ config: bot,
80
+ api,
81
+ log,
82
+ routes,
83
+ alwaysAllow,
84
+ inbound,
85
+ persona,
86
+ botId: bot.id,
87
+ isDirector: (sessionId) => personaLib.isRoleDirectorSession(bot.roleId, sessionId),
88
+ });
89
+ outbound.bind(ctx);
90
+ const onSlashCommand = createSlashHandler({
91
+ log, alwaysAllow, threads, agents: deps.agents, approval: deps.approval,
92
+ outbound, agentPresets: deps.agentPresets, botId: bot.id,
93
+ });
94
+ const presetOverride = (typeof bot.agentPreset === 'string' && bot.agentPreset.length > 0)
95
+ ? bot.agentPreset
96
+ : 'standard';
97
+ const setupDeps = {
98
+ log,
99
+ api,
100
+ routes,
101
+ outbound,
102
+ workspaceRegistry: deps.workspaceRegistry,
103
+ persona,
104
+ roleId: bot.roleId,
105
+ defaultCwd: process.cwd(),
106
+ resolvePreset: deps.agentPresets === undefined
107
+ ? undefined
108
+ : async (sessionId) => {
109
+ let presetId = presetOverride;
110
+ const openid = persona.openidFromSessionId(sessionId);
111
+ if (openid !== undefined) {
112
+ try {
113
+ const role = await persona.loadRole(bot.roleId);
114
+ if (role && role.binding.openid === openid && role.persona?.name) {
115
+ presetId = 'pygmalion-director';
116
+ }
117
+ }
118
+ catch (error) {
119
+ log.warn('pygmalion loadRole failed for %s: %o', openid, error);
120
+ }
121
+ }
122
+ return deps.agentPresets.resolve(threads.presetFor(sessionId) ?? presetId);
123
+ },
124
+ agentPresets: deps.agentPresets,
125
+ httpApiToken: bot.httpApiToken,
126
+ httpApiPath: bot.httpApiPath,
127
+ director: deps.director,
128
+ };
129
+ const setupAgent = createSetupAgent(setupDeps);
130
+ // 已存在 agent(dsh 核心冷恢复/重组合创建,未走 pygmalion setup)时,ensureAgent
131
+ // 命中既有分支不会执行 setup → standing 导演工具缺会话上下文。此回调只补登记
132
+ // sessionDeps(不重挂 preset——mount 对已绑定 agent 会 throw),幂等可重复调用。
133
+ const registerSessionContext = (sessionId) => {
134
+ const directorSvc = deps.director?.get?.('pygmalion.director');
135
+ if (directorSvc === undefined || typeof directorSvc.registerSession !== 'function') return;
136
+ directorSvc.registerSession(sessionId, buildSessionDeps(setupDeps, sessionId));
137
+ };
138
+ // 冷恢复兜底(修 D19):重启后 dsh 核心重建既有 agent 不触发 setup/ensureAgent(无入站
139
+ // 消息),sessionDeps 永不登记。向宿主登记惰性构造器,depsFor 未命中时按 sessionId
140
+ // 现场构造并缓存(buildSessionDeps 除 target 惰性闭包外全是本 bot 常量,任意会话可构造)。
141
+ const directorSvc = deps.director?.get?.('pygmalion.director');
142
+ if (directorSvc !== undefined && typeof directorSvc.registerSessionBuilder === 'function') {
143
+ directorSvc.registerSessionBuilder(bot.id, (sessionId) => buildSessionDeps(setupDeps, sessionId));
144
+ }
145
+ inbound.attachHooks({ onSlashCommand, setupAgent, registerSessionContext });
146
+
147
+ // 可选 HTTP 推送/唤醒 API:按 botId 自动生成 path,token 由 BotManager 生成。
148
+ // 宿主无 webServer 时跳过挂载(status 标 unavailable),不 throw。
149
+ let httpApiMount;
150
+ let httpApiUnavailable = false;
151
+ if (bot.httpApiToken) {
152
+ httpApiMount = resolveHttpApiMount({ path: bot.httpApiPath, token: bot.httpApiToken });
153
+ if (deps.webServer === undefined) {
154
+ httpApiMount = undefined;
155
+ httpApiUnavailable = true;
156
+ log.warn('pygmalion: bot %s 配置了 httpApiToken,但宿主无 webServer(该 API 仅在 dsh web 等 Web 组合下可用),已跳过挂载', bot.id);
157
+ }
158
+ }
159
+
160
+ let status = { state: 'stopped', detail: '' };
161
+ const setStatus = (state, detail = '') => { status = { state, detail }; };
162
+
163
+ const gateway = new QQGateway(bot, api, {
164
+ onMessage: (payload, eventType) => {
165
+ const message = normalizeMessage(payload, eventType);
166
+ if (message === undefined)
167
+ return;
168
+ void inbound.handle(message).catch((error) => {
169
+ log.error('inbound handling failed (%s): %o', bot.id, error);
170
+ });
171
+ },
172
+ onInteraction: (payload) => {
173
+ const interaction = asInteractionButton(payload);
174
+ if (interaction === undefined)
175
+ return;
176
+ if (outbound.handleApprovalCallback(interaction.buttonData) !== undefined) {
177
+ void api.ackInteraction(interaction.id).catch((error) => {
178
+ log.warn('interaction ack failed: %o', error);
179
+ });
180
+ }
181
+ },
182
+ onReady: () => { log.info('QQ gateway ready (bot=%s appid=%s)', bot.id, api.appId()); },
183
+ onStatus: setStatus,
184
+ }, log, join(deps.storages, `${ns}-gateway-session.json`));
185
+
186
+ const facade = {
187
+ botId: bot.id,
188
+ roleId: bot.roleId,
189
+ routes,
190
+ threads,
191
+ inbound,
192
+ withinChatWindowMs: bot.withinChatWindowMs,
193
+ httpApiToken: bot.httpApiToken,
194
+ };
195
+
196
+ let dispose = null;
197
+ let started = false;
198
+ let stopping = false;
199
+
200
+ function start() {
201
+ if (started || stopping)
202
+ return;
203
+ started = true;
204
+ // ctx.effect 返回 disposer;effect 运行时 fiber 活跃,ctx.on / webServer.register 均合法。
205
+ dispose = ctx.effect(() => {
206
+ const stops = [];
207
+ void refIndex.init();
208
+ void routes.load().then(() => {
209
+ try {
210
+ routes.prune(ROUTE_TTL);
211
+ alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
212
+ }
213
+ catch { /* ignore */ }
214
+ });
215
+ void alwaysAllow.load();
216
+ void threads.load();
217
+ void gateway.start();
218
+ const pruneTimer = setInterval(() => {
219
+ try {
220
+ routes.prune(ROUTE_TTL);
221
+ alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
222
+ }
223
+ catch { /* ignore */ }
224
+ }, 6 * 3600 * 1000);
225
+ pruneTimer.unref?.();
226
+ stops.push(() => clearInterval(pruneTimer));
227
+ const onDisposed = ctx.on('agent/disposed', ({ agent }) => {
228
+ if (!agent.id.startsWith(`${SESSION_PREFIX}:${bot.id}:`))
229
+ return;
230
+ deps.director?.get?.('pygmalion.director')?.unregisterSession?.(agent.id);
231
+ void outbound.closeStream(agent.id);
232
+ inbound.onAgentDisposed(agent.id);
233
+ });
234
+ stops.push(() => { if (typeof onDisposed === 'function') onDisposed(); });
235
+ if (httpApiMount !== undefined && deps.webServer !== undefined) {
236
+ stops.push(deps.webServer.register({
237
+ kind: 'prefix',
238
+ path: httpApiMount.path,
239
+ handler: createHttpApiHandler({
240
+ mountPath: httpApiMount.path,
241
+ token: httpApiMount.token,
242
+ config: bot,
243
+ log,
244
+ api,
245
+ routes,
246
+ threads,
247
+ ensureAgent: (sessionId) => inbound.ensureAgent(sessionId),
248
+ persona,
249
+ botId: bot.id,
250
+ roleId: bot.roleId,
251
+ activityAt: (sessionId) => inbound.userActivityAt(sessionId),
252
+ withinChatWindowMs: bot.withinChatWindowMs,
253
+ scriptWakeMinIntervalMs: config?.heartbeat?.scriptWakeMinIntervalMs ?? 600000,
254
+ }),
255
+ }));
256
+ log.info('pygmalion: httpApi mounted for bot %s at %s', bot.id, httpApiMount.path);
257
+ }
258
+ return () => {
259
+ stops.forEach((fn) => { try { fn(); } catch { /* ignore */ } });
260
+ outbound.disposeAllStreams();
261
+ inbound.dispose();
262
+ gateway.dispose();
263
+ api.dispose();
264
+ void outbound.dispose();
265
+ started = false;
266
+ dispose = null;
267
+ setStatus('stopped');
268
+ };
269
+ }, `pygmalion.bot:${bot.id}()`);
270
+ return dispose;
271
+ }
272
+
273
+ function stop() {
274
+ stopping = true;
275
+ const d = dispose;
276
+ dispose = null;
277
+ try { if (typeof d === 'function') d(); } catch { /* ignore */ }
278
+ stopping = false;
279
+ }
280
+
281
+ return { bot, facade, getStatus: () => status, start, stop, httpApiUnavailable };
282
+ }
package/src/bots.js ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Pygmalion 正式版动态 Bot 管理:QQ 机器人凭据在管理网页配置(角色 owner 私有)。
3
+ *
4
+ * bot 记录持久化在 data/bots/<botId>.json,插件运行时按记录动态启停接入管线。
5
+ *
6
+ * botId = 'bot-' + safeId(roleId) — 确定性派生:删了重建 store 文件与会话 id 连续
7
+ * httpApiPath = /external/qq/<botId> — 按 botId 唯一,避免 webServer.register 重复 path
8
+ * httpApiToken = randomBytes(24).hex — 自动生成;生活脚本经 PYG_TOKEN 环境变量自动获得
9
+ *
10
+ * 每 bot 一个串行操作队列(enqueue),防止并发 upsert/remove 竞态。update 若改到运行时
11
+ * 字段(config 部分变化)→ 先停旧管线再重建启动。qqSecret 永不回传(网页只存不读)。
12
+ */
13
+ import { randomBytes } from 'node:crypto';
14
+ import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
15
+ import { join } from 'node:path';
16
+ import { BotConfig } from './config.js';
17
+ import { atomicWrite, dataRoot, safeId } from './persona.js';
18
+
19
+ async function readJson(file, fallback) {
20
+ try { return JSON.parse(await readFile(file, 'utf8')); } catch { return fallback; }
21
+ }
22
+ function atomicWriteJson(file, value) {
23
+ return atomicWrite(file, JSON.stringify(value ?? {}, null, 2));
24
+ }
25
+
26
+ /** 网页可编辑的运行时字段(其余由系统派生/内部持有)。 */
27
+ const EDITABLE_FIELDS = ['sandbox', 'withinChatWindowMs', 'streaming', 'enabled'];
28
+
29
+ /**
30
+ * @param deps {
31
+ * config // 插件 Config(legacy config.bots 迁移源,可无)
32
+ * log // 日志
33
+ * persona // persona 库(dataRoot/safeId/atomicWrite)
34
+ * dataRoot? // 覆盖数据根(测试用)
35
+ * buildPipeline // (record) => { facade, getStatus(), start(), stop(), httpApiUnavailable? }
36
+ * // (index.js 里封装 createBotPipeline,record 已过 BotConfig schema)
37
+ * }
38
+ */
39
+ export function createBotManager(deps) {
40
+ const { config, log, persona, buildPipeline } = deps;
41
+ const dataDir = deps.dataRoot ?? persona.dataRoot();
42
+ const dir = join(dataDir, 'bots');
43
+
44
+ const records = new Map(); // botId -> 规范化记录
45
+ const pipelines = new Map(); // botId -> 存活管线
46
+ const queues = new Map(); // botId -> 串行操作 Promise 链
47
+ let alive = false; // 启动期开关:stopAll 打断未完成的 startAll 时阻止后续管线再起
48
+
49
+ function botIdForRole(roleId) { return `bot-${safeId(roleId)}`; }
50
+ function botPath(botId) { return join(dir, `${botId}.json`); }
51
+
52
+ /** 入队串行操作:上一个完成后再执行 fn,错误不污染队列。 */
53
+ function enqueue(botId, fn) {
54
+ const prev = queues.get(botId) ?? Promise.resolve();
55
+ const next = prev.catch(() => {}).then(fn);
56
+ queues.set(botId, next.catch(() => {}));
57
+ return next;
58
+ }
59
+
60
+ /**
61
+ * 规范化记录:BotConfig 部分过 schema(校验 + 补默认值),剥离并回填 meta 字段。
62
+ * 非法 → null(带日志,不 throw,避免单个坏记录拖垮整批加载)。
63
+ */
64
+ function normalizeRecord(raw) {
65
+ const base = { ...raw };
66
+ const meta = {
67
+ owner: base.owner,
68
+ enabled: base.enabled,
69
+ createdAt: base.createdAt,
70
+ updatedAt: base.updatedAt,
71
+ };
72
+ for (const k of ['owner', 'enabled', 'createdAt', 'updatedAt']) delete base[k];
73
+ const result = BotConfig['~standard'].validate(base);
74
+ if (result.issues && result.issues.length) {
75
+ log?.warn?.('pygmalion: bot 记录 %s 非法: %s', raw?.id, result.issues.map((i) => i.message).join('; '));
76
+ return null;
77
+ }
78
+ return {
79
+ ...result.value,
80
+ owner: meta.owner,
81
+ enabled: meta.enabled !== false,
82
+ createdAt: meta.createdAt ?? Date.now(),
83
+ updatedAt: meta.updatedAt ?? Date.now(),
84
+ };
85
+ }
86
+
87
+ /** 运行时部分(不含 meta 字段)JSON 串:判断更新是否需要重建管线。 */
88
+ function configKey(rec) {
89
+ const c = { ...rec };
90
+ for (const k of ['owner', 'enabled', 'createdAt', 'updatedAt']) delete c[k];
91
+ return JSON.stringify(c);
92
+ }
93
+
94
+ async function loadAll() {
95
+ await mkdir(dir, { recursive: true });
96
+ let names;
97
+ try { names = await readdir(dir); } catch { names = []; }
98
+ for (const name of names) {
99
+ if (!name.endsWith('.json')) continue;
100
+ const id = name.slice(0, -5);
101
+ const rec = normalizeRecord(await readJson(botPath(id), null));
102
+ if (rec) records.set(id, rec);
103
+ }
104
+ }
105
+
106
+ /** 一次性迁移配置里的 bots[](兼容旧部署格式)到数据目录。 */
107
+ async function migrateLegacy() {
108
+ const legacy = Array.isArray(config?.bots) ? config.bots : [];
109
+ for (const b of legacy) {
110
+ if (!b || typeof b !== 'object' || !b.roleId) continue;
111
+ const botId = botIdForRole(b.roleId);
112
+ if (records.has(botId)) continue; // 已有网页配置优先
113
+ const rec = normalizeRecord({ ...b, id: botId });
114
+ if (!rec) { log?.warn?.('pygmalion: legacy bot %s 非法,跳过迁移', b?.id); continue; }
115
+ if (!rec.httpApiPath) rec.httpApiPath = `/external/qq/${botId}`;
116
+ if (!rec.httpApiToken) rec.httpApiToken = randomBytes(24).toString('hex');
117
+ rec.createdAt = Date.now();
118
+ rec.updatedAt = Date.now();
119
+ records.set(botId, rec);
120
+ await atomicWriteJson(botPath(botId), rec);
121
+ log?.info?.('pygmalion: 迁移 legacy bot %s → %s', b.id, botId);
122
+ }
123
+ }
124
+
125
+ async function startPipeline(botId, record) {
126
+ if (!alive) return;
127
+ try {
128
+ const pipeline = buildPipeline(record);
129
+ pipeline.start();
130
+ pipelines.set(botId, pipeline);
131
+ log?.info?.('pygmalion: bot %s 已启动(role=%s)', botId, record.roleId);
132
+ }
133
+ catch (error) {
134
+ log?.error?.('pygmalion: bot %s 启动失败: %o', botId, error);
135
+ throw error;
136
+ }
137
+ }
138
+ function stopPipeline(botId) {
139
+ const p = pipelines.get(botId);
140
+ if (!p) return;
141
+ pipelines.delete(botId);
142
+ try { p.stop(); } catch { /* ignore */ }
143
+ }
144
+
145
+ /** 启动所有记录:先加载 + 迁移配置,再启所有 enabled 管线。 */
146
+ async function startAll() {
147
+ if (alive) return;
148
+ alive = true;
149
+ await loadAll();
150
+ await migrateLegacy();
151
+ for (const [botId, rec] of records) {
152
+ if (!alive) return; // 已被 stopAll 打断,放弃后续启动
153
+ if (rec.enabled === false) continue;
154
+ try { await startPipeline(botId, rec); }
155
+ catch { /* 单 bot 失败不阻断其余 */ }
156
+ }
157
+ }
158
+ function stopAll() {
159
+ alive = false;
160
+ for (const botId of [...pipelines.keys()]) stopPipeline(botId);
161
+ records.clear();
162
+ }
163
+
164
+ function statusOf(botId) {
165
+ const p = pipelines.get(botId);
166
+ if (p) return p.getStatus();
167
+ return records.has(botId) ? { state: 'stopped', detail: '' } : { state: 'missing', detail: '' };
168
+ }
169
+
170
+ /** 网页可见记录(脱敏:不含 qqSecret)。 */
171
+ function publicRecord(rec) {
172
+ const pipeline = pipelines.get(rec.id);
173
+ return {
174
+ botId: rec.id,
175
+ roleId: rec.roleId,
176
+ qqAppId: rec.qqAppId,
177
+ sandbox: rec.sandbox,
178
+ withinChatWindowMs: rec.withinChatWindowMs,
179
+ streaming: rec.streaming,
180
+ httpApiPath: rec.httpApiPath,
181
+ httpApiToken: rec.httpApiToken,
182
+ enabled: rec.enabled,
183
+ httpApiUnavailable: pipeline?.httpApiUnavailable === true,
184
+ status: statusOf(rec.id),
185
+ owner: rec.owner,
186
+ createdAt: rec.createdAt,
187
+ updatedAt: rec.updatedAt,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * 创建/更新某角色的机器人(botId 由 roleId 派生,天然一角色一机器人)。
193
+ * input.qqSecret 为空 = 保持原值;首次配置必须提供。运行时字段变化 → 停旧管线重建启动。
194
+ */
195
+ async function upsertForRole(roleId, input) {
196
+ const rid = safeId(String(roleId ?? '').trim());
197
+ if (!rid) throw new Error('roleId 非法');
198
+ const botId = botIdForRole(rid);
199
+ return enqueue(botId, async () => {
200
+ const existing = records.get(botId);
201
+ const secret = input.qqSecret && String(input.qqSecret).trim()
202
+ ? String(input.qqSecret).trim()
203
+ : existing?.qqSecret;
204
+ if (!existing && !secret) throw new Error('首次配置必须提供 AppSecret');
205
+ if (!String(input.qqAppId ?? existing?.qqAppId ?? '').trim()) throw new Error('必须提供 QQ 开放平台 AppID');
206
+
207
+ const base = {
208
+ ...(existing ?? {}),
209
+ id: botId,
210
+ roleId: rid,
211
+ qqAppId: String(input.qqAppId ?? existing?.qqAppId).trim(),
212
+ qqSecret: secret,
213
+ };
214
+ for (const f of EDITABLE_FIELDS) if (input[f] !== undefined) base[f] = input[f];
215
+ if (input.owner !== undefined) base.owner = input.owner;
216
+ const rec = normalizeRecord(base);
217
+ if (!rec) throw new Error('bot 配置无效');
218
+
219
+ if (!existing) {
220
+ rec.httpApiPath = `/external/qq/${botId}`;
221
+ rec.httpApiToken = randomBytes(24).toString('hex');
222
+ rec.createdAt = Date.now();
223
+ }
224
+ rec.updatedAt = Date.now();
225
+ await atomicWriteJson(botPath(botId), rec);
226
+
227
+ const rebuild = !existing || configKey(rec) !== configKey(existing);
228
+ records.set(botId, rec);
229
+ if (rec.enabled === false) {
230
+ stopPipeline(botId);
231
+ }
232
+ else if (rebuild) {
233
+ stopPipeline(botId);
234
+ await startPipeline(botId, rec);
235
+ }
236
+ return publicRecord(rec);
237
+ });
238
+ }
239
+
240
+ async function removeForRole(roleId) {
241
+ const botId = botIdForRole(roleId);
242
+ return enqueue(botId, async () => {
243
+ stopPipeline(botId);
244
+ records.delete(botId);
245
+ await rm(botPath(botId), { force: true });
246
+ return { ok: true, botId };
247
+ });
248
+ }
249
+ async function removeBot(botId) {
250
+ return enqueue(botId, async () => {
251
+ stopPipeline(botId);
252
+ records.delete(botId);
253
+ await rm(botPath(botId), { force: true });
254
+ return { ok: true, botId };
255
+ });
256
+ }
257
+
258
+ /** 全部记录(网页列表,脱敏)。 */
259
+ function getBots() { return [...records.values()].map(publicRecord); }
260
+ /** 存活管线 facade(heartbeat 消费:routes/threads/inbound/withinChatWindowMs/httpApiToken)。 */
261
+ function getPipelines() { return [...pipelines.values()].map((p) => p.facade).filter(Boolean); }
262
+ /** 某角色的机器人记录(脱敏)或 null。 */
263
+ function recordForRole(roleId) {
264
+ const rec = records.get(botIdForRole(roleId));
265
+ return rec ? publicRecord(rec) : null;
266
+ }
267
+
268
+ return {
269
+ startAll, stopAll,
270
+ upsertForRole, removeForRole, removeBot,
271
+ getBots, getPipelines, statusOf, recordForRole,
272
+ };
273
+ }
package/src/config.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Pygmalion 正式版插件配置 schema。
3
+ *
4
+ * 结构:
5
+ * web — 管理网页(唯一公网暴露面,默认仅本机)
6
+ * heartbeat — 内置心跳全局默认(每角色 proactive.json 可覆盖)
7
+ * bots[] — 兼容旧部署格式的迁移源:一次性并入数据目录 data/bots/,
8
+ * 机器人凭据从此在管理网页配置(见 src/bots.js)
9
+ */
10
+ import Schema from '@deepseek-ai/schemastery';
11
+
12
+ /** Default QQ gateway intents: public channel messages + group/C2C + interactions + DMs. */
13
+ export const DEFAULT_INTENTS = (1 << 30) + (1 << 25) + (1 << 26) + (1 << 12);
14
+
15
+ /** 单个机器人实例配置(继承 dsh-qqbot-community 适配器,去掉 demo 的扁平 provider/model/cwd)。 */
16
+ export const BotConfig = Schema.object({
17
+ id: Schema.string().required().description('bot 实例 id(store 文件名隔离,避免多机器人数据串)'),
18
+ roleId: Schema.string().required().description('该机器人服务哪个角色(对应 data/roles/<roleId>)'),
19
+ qqAppId: Schema.string().required().description('QQ 开放平台机器人 AppID(字符串,YAML 中加引号)'),
20
+ qqSecret: Schema.string().required().description('QQ 开放平台机器人 AppSecret'),
21
+ sandbox: Schema.boolean().default(true).description('是否使用 QQ 沙箱环境'),
22
+ endpoint: Schema.string().default('https://api.sgroup.qq.com').description('QQ OpenAPI 接入点'),
23
+ intents: Schema.number().default(DEFAULT_INTENTS).description('网关事件订阅掩码'),
24
+ agentPreset: Schema.string().default('standard').description('非角色会话的默认 agent preset id'),
25
+ debug: Schema.boolean().default(false).description('调试日志'),
26
+ allowFrom: Schema.array(Schema.string()).default(['*']).description("C2C 发送者 openid 白名单('*' 通配)"),
27
+ groupAllowFrom: Schema.array(Schema.string()).default(['*']).description('群 openid 白名单'),
28
+ markdown: Schema.boolean().default(false).description('以 markdown (msg_type 2) 发送回复,需开通权限'),
29
+ textChunkLimit: Schema.number().default(4000).description('单条静态回复的最大字符数'),
30
+ typing: Schema.boolean().default(true).description('C2C 输入中指示(60s 窗口自动续发)'),
31
+ streaming: Schema.boolean().default(false).description('C2C 流式回复;导演会话一律关闭(修 D16,原 patch-home-streaming 移除)'),
32
+ streamThrottleMs: Schema.number().default(1200).description('流式帧最小间隔(毫秒)'),
33
+ deliverWindowMs: Schema.number().default(900).description('同一轮内多条文本回复的合并窗口(毫秒)'),
34
+ deliverMaxWaitMs: Schema.number().default(6000).description('合并回复的最大等待(毫秒)'),
35
+ replyPassiveLimit: Schema.number().default(4).description('每条入站消息允许的被动回复次数'),
36
+ mediaDownload: Schema.boolean().default(true).description('下载非图片入站附件到工作区 .qq-media/'),
37
+ stt: Schema.object({
38
+ baseUrl: Schema.string().default('https://api.openai.com/v1').description('OpenAI 兼容 STT base URL'),
39
+ apiKey: Schema.string().description('STT API key(缺失时整体视为未启用)'),
40
+ model: Schema.string().default('whisper-1').description('STT 模型'),
41
+ }).description('语音转文字配置'),
42
+ approval: Schema.boolean().default(true).description('为 QQ 会话注册内联键盘审批 answerer'),
43
+ approvalTimeoutMs: Schema.number().default(300000).description('审批按钮等待超时(毫秒)'),
44
+ slashCommands: Schema.boolean().default(true).description('启用 /help /ping /me /new /presets /approve /always 命令'),
45
+ httpApiPath: Schema.string().default('/external/qq/bot-1').description('该机器人的 HTTP 推送/唤醒 API 路由前缀(多机器人必须互不相同)'),
46
+ httpApiToken: Schema.string().description('该机器人 HTTP API 的 Bearer 鉴权 token(至少 8 字符;缺省则不挂载,生活脚本 HTTP hook 需要它)'),
47
+ keyboardGroupId: Schema.string().default('dshqq').description('内联键盘按钮 action.group_id(审批键盘;配置化以免与其它应用冲突)'),
48
+ withinChatWindowMs: Schema.number().default(300000).description('唤醒撞车检测窗口:距最后一次用户消息不足此毫秒数则跳过唤醒'),
49
+ });
50
+
51
+ export const Config = Schema.object({
52
+ web: Schema.object({
53
+ host: Schema.string().default('127.0.0.1').description('管理网页监听地址(公网部署配 0.0.0.0 + HTTPS 反代)'),
54
+ port: Schema.number().default(4180).description('管理网页监听端口'),
55
+ }).description('管理网页(插件内置独立 HTTP 服务)'),
56
+ heartbeat: Schema.object({
57
+ enabled: Schema.boolean().default(true).description('内置心跳总开关'),
58
+ intervalMs: Schema.number().default(30000).description('心跳扫描间隔(毫秒)'),
59
+ archiveIdleMinutes: Schema.number().default(45).description('用户连续多少分钟未发消息则触发记忆归档(0=关,角色级可覆盖)'),
60
+ eveningCheck: Schema.string().default('20:00').description('「今日未联系」主动问候的起始时刻 HH:MM'),
61
+ lifeEnabled: Schema.boolean().default(true).description('生活脚本总开关'),
62
+ lifeMaxPerDay: Schema.number().default(2).description('(已废弃:插件不再限制脚本运行次数)保留字段仅为兼容旧配置,不再被消费'),
63
+ lifeIntervalMs: Schema.number().default(1800000).description('非零性破坏后重试提示「生活脚本未在运行」的最小间隔(毫秒,默认 30 分钟);每次 dsh 启动后首个心跳 tick 无视此间隔立刻提示一次,防跨重启陈旧节流压制'),
64
+ scriptWakeMinIntervalMs: Schema.number().default(600000).description('生活脚本 wake() 报事件后,同一角色再次唤醒 dsh 的最小间隔(毫秒),防脚本循环轰炸'),
65
+ }).description('内置心跳(主动唤醒 + 沉默归档 + 非零性检查 + rewake 到期)'),
66
+ bots: Schema.array(BotConfig).description('兼容旧部署格式:一次性迁移到 data/bots/,此后凭据在管理网页配置'),
67
+ });