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,392 @@
1
+ import { nextMsgSeq } from './qqapi.js';
2
+ import { SESSION_PREFIX, targetOfSession } from './inbound.js';
3
+ /** Strip internal scaffolding tags models sometimes emit. */
4
+ const INTERNAL_TAGS = [
5
+ /<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,
6
+ /<previous_response\b[^>]*>[\s\S]*?<\/previous_response>/gi,
7
+ /<\s*\/?\s*(?:system-reminder|previous_response)\b[^>]*\/?\s*>/gi,
8
+ /`think`[\s\S]*?`\/think`/gi,
9
+ /<\s*\/?\s*think\b[^>]*\/?\s*>/gi,
10
+ /<thinking\b[^>]*>[\s\S]*?<\/thinking>/gi,
11
+ /<\s*\/?\s*thinking\b[^>]*\/?\s*>/gi,
12
+ ];
13
+ export function sanitizeOut(text) {
14
+ let result = text;
15
+ for (const pattern of INTERNAL_TAGS)
16
+ result = result.replace(pattern, '');
17
+ return result.trim();
18
+ }
19
+ /** Split long text on paragraph/sentence boundaries close to the limit. */
20
+ export function chunkText(text, limit) {
21
+ if (text.length <= limit)
22
+ return [text];
23
+ const chunks = [];
24
+ let rest = text;
25
+ while (rest.length > limit) {
26
+ let cut = -1;
27
+ for (const marker of ['\n\n', '\n', '。', ';', '. ', ' ']) {
28
+ const index = rest.lastIndexOf(marker, limit);
29
+ if (index > limit * 0.3) {
30
+ cut = index + marker.length;
31
+ break;
32
+ }
33
+ }
34
+ if (cut <= 0)
35
+ cut = limit;
36
+ chunks.push(rest.slice(0, cut));
37
+ rest = rest.slice(cut);
38
+ }
39
+ if (rest.length > 0)
40
+ chunks.push(rest);
41
+ return chunks;
42
+ }
43
+ function prefixMatches(accepted, incoming) {
44
+ if (incoming.startsWith(accepted))
45
+ return true;
46
+ return incoming.replace(/\s+/g, ' ').startsWith(accepted.replace(/\s+/g, ' '));
47
+ }
48
+ function longestCommonPrefix(a, b) {
49
+ let i = 0;
50
+ while (i < a.length && i < b.length && a[i] === b[i])
51
+ i++;
52
+ return i;
53
+ }
54
+ export class OutboundPipeline {
55
+ deps;
56
+ /** Streaming state per session (one live step at a time). */
57
+ streams = new Map();
58
+ /** Debounce buffers per session. */
59
+ buffers = new Map();
60
+ /** Pending approval decisions keyed by button-data token. */
61
+ pendingApprovals = new Map();
62
+ /** Per-session director 判定缓存(绑定在会话内不变)。 */
63
+ directorCache = new Map();
64
+ constructor(deps) {
65
+ this.deps = deps;
66
+ }
67
+ /** 角色级导演判定(带缓存)。无 deps.isDirector 时视为非导演。 */
68
+ async isDirector(sessionId) {
69
+ if (this.directorCache.has(sessionId))
70
+ return this.directorCache.get(sessionId);
71
+ const result = (await this.deps.isDirector?.(sessionId)) === true;
72
+ this.directorCache.set(sessionId, result);
73
+ return result;
74
+ }
75
+ /** Register the session-event listener on the plugin context. */
76
+ bind(ctx) {
77
+ const onEvent = ctx.on;
78
+ onEvent('session/event', (session, event) => {
79
+ // 只处理本 bot 前缀的会话(多 bot 隔离:每个 outbound 只响应自己 bot 的事件)。
80
+ if (!session.id.startsWith(`${SESSION_PREFIX}:${this.deps.botId}:`))
81
+ return;
82
+ void this.handleEvent(session.id, event).catch((error) => {
83
+ this.deps.log.error('outbound event handling failed for %s: %o', session.id, error);
84
+ });
85
+ });
86
+ }
87
+ async handleEvent(sessionId, event) {
88
+ const target = this.targetOf(sessionId);
89
+ if (event.type === 'assistant/message' || event.type === 'turn/end') {
90
+ this.deps.log.info('QQ outbound: %s session=%s target=%s', event.type, sessionId, target.kind);
91
+ }
92
+ if (event.type === 'turn/start') {
93
+ this.resetTurn(sessionId);
94
+ return;
95
+ }
96
+ if (event.type === 'turn/end') {
97
+ this.resetTurn(sessionId);
98
+ this.deps.inbound.stopTyping(sessionId);
99
+ return;
100
+ }
101
+ if (event.type === 'assistant/chunk') {
102
+ // 导演会话不做流式上屏(发送只经 director_send 工具)
103
+ if (await this.isDirector(sessionId))
104
+ return;
105
+ const chunk = event.data.chunk;
106
+ if (chunk?.type === 'text-delta' && typeof chunk.text === 'string' && target.kind === 'c2c' && this.deps.config.streaming !== false) {
107
+ this.onStreamDelta(sessionId, chunk.text);
108
+ }
109
+ return;
110
+ }
111
+ if (event.type === 'assistant/message') {
112
+ const text = sanitizeOut((event.data.message?.content ?? [])
113
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
114
+ .map((block) => block.text)
115
+ .join(''));
116
+ await this.onAssistantMessage(sessionId, text);
117
+ return;
118
+ }
119
+ }
120
+ targetOf(sessionId) {
121
+ const live = this.deps.routes.get(sessionId);
122
+ return live?.target ?? targetOfSession(sessionId);
123
+ }
124
+ resetTurn(sessionId) {
125
+ const stream = this.streams.get(sessionId);
126
+ if (stream !== undefined) {
127
+ // The turn ended without an assistant/message (e.g. aborted): finalize
128
+ // whatever was streamed so QQ does not keep a "generating" bubble.
129
+ if (stream.sentFrames > 0 && !stream.failed) {
130
+ void this.sendStreamFrame(sessionId, stream, stream.lastAccepted, 10);
131
+ }
132
+ this.streams.delete(sessionId);
133
+ }
134
+ this.flushBuffer(sessionId, true);
135
+ }
136
+ /**
137
+ * Force-close any in-flight C2C stream for `sessionId` by sending the
138
+ * DONE (input_state=10) frame. Called from `agent/disposed` (so a
139
+ * disposed/cancelled agent does not leave a "generating" bubble on QQ)
140
+ * and from `/new` (so the abandoned session id can be reused).
141
+ */
142
+ async closeStream(sessionId) {
143
+ const stream = this.streams.get(sessionId);
144
+ if (stream === undefined)
145
+ return;
146
+ if (stream.sentFrames > 0 && !stream.failed) {
147
+ try {
148
+ await this.sendStreamFrame(sessionId, stream, stream.lastAccepted, 10);
149
+ }
150
+ catch (error) {
151
+ this.deps.log.warn('QQ closeStream on %s failed: %o', sessionId, error);
152
+ }
153
+ }
154
+ this.streams.delete(sessionId);
155
+ }
156
+ /** Close every active stream; used during plugin teardown. */
157
+ async disposeAllStreams() {
158
+ for (const sessionId of [...this.streams.keys()]) {
159
+ await this.closeStream(sessionId).catch(() => undefined);
160
+ }
161
+ }
162
+ // ── Streaming (C2C replace mode) ───────────────────────────────────────────
163
+ onStreamDelta(sessionId, delta) {
164
+ let stream = this.streams.get(sessionId);
165
+ if (stream === undefined) {
166
+ const anchor = this.deps.routes.get(sessionId);
167
+ if (anchor?.lastMsgId === undefined)
168
+ return; // no passive anchor: skip streaming
169
+ stream = {
170
+ msgSeq: nextMsgSeq(),
171
+ index: 0,
172
+ lastAccepted: '',
173
+ sentFrames: 0,
174
+ failed: false,
175
+ lastSentAt: 0,
176
+ };
177
+ this.streams.set(sessionId, stream);
178
+ }
179
+ if (stream.failed)
180
+ return;
181
+ const candidate = prefixMatches(stream.lastAccepted, delta)
182
+ ? delta
183
+ : stream.lastAccepted + delta.slice(longestCommonPrefix(stream.lastAccepted, delta));
184
+ const throttle = this.deps.config.streamThrottleMs ?? 1_200;
185
+ if (Date.now() - stream.lastSentAt < throttle)
186
+ return;
187
+ void this.sendStreamFrame(sessionId, stream, candidate, 1);
188
+ }
189
+ async sendStreamFrame(sessionId, stream, text, state) {
190
+ const target = this.targetOf(sessionId);
191
+ if (target.kind !== 'c2c')
192
+ return;
193
+ const anchor = this.deps.routes.get(sessionId);
194
+ const msgId = anchor?.lastMsgId;
195
+ if (msgId === undefined)
196
+ return;
197
+ try {
198
+ const streamMsgId = await this.deps.api.sendStreamFrame(target.userId, {
199
+ msgSeq: stream.msgSeq,
200
+ index: stream.index,
201
+ text,
202
+ state,
203
+ msgId,
204
+ streamMsgId: stream.streamMsgId,
205
+ });
206
+ stream.index += 1;
207
+ stream.lastAccepted = text;
208
+ stream.lastSentAt = Date.now();
209
+ stream.sentFrames += 1;
210
+ if (streamMsgId !== undefined && stream.streamMsgId === undefined)
211
+ stream.streamMsgId = streamMsgId;
212
+ }
213
+ catch (error) {
214
+ stream.failed = true;
215
+ this.deps.log.warn('QQ stream frame failed; falling back to static delivery: %o', error);
216
+ }
217
+ }
218
+ // ── Static delivery with debounce ──────────────────────────────────────────
219
+ async onAssistantMessage(sessionId, text) {
220
+ // ── Pygmalion 导演模式:最终文本一律不发送 ────────────────────────────
221
+ // 导演的"对用户说的话"只能通过 director_send 工具发出;任何最终文本
222
+ // (思考、计划、动作叙述)都不会作为消息送达,杜绝过程性内容外泄。
223
+ if (await this.isDirector(sessionId)) {
224
+ this.resetTurn(sessionId);
225
+ this.deps.inbound.stopTyping(sessionId);
226
+ return;
227
+ }
228
+ const stream = this.streams.get(sessionId);
229
+ if (stream !== undefined && !stream.failed && stream.sentFrames > 0 && text.length > 0) {
230
+ // The streamed bubble already shows this text: close it as DONE and let
231
+ // the rendered content stand (QQ replace mode keeps the final frame).
232
+ if (prefixMatches(text, stream.lastAccepted) || stream.lastAccepted.startsWith(text)) {
233
+ await this.sendStreamFrame(sessionId, stream, text.length >= stream.lastAccepted.length ? text : stream.lastAccepted, 10);
234
+ this.streams.delete(sessionId);
235
+ return;
236
+ }
237
+ // Diverged (model rewrote): finalize what was streamed, then send the
238
+ // authoritative text as a static follow-up message.
239
+ await this.sendStreamFrame(sessionId, stream, stream.lastAccepted, 10);
240
+ this.streams.delete(sessionId);
241
+ }
242
+ if (text.length === 0)
243
+ return;
244
+ const window = this.deps.config.deliverWindowMs ?? 900;
245
+ const maxWait = this.deps.config.deliverMaxWaitMs ?? 6_000;
246
+ let buffer = this.buffers.get(sessionId);
247
+ if (buffer === undefined) {
248
+ buffer = { texts: [], firstAt: Date.now(), flushed: false };
249
+ this.buffers.set(sessionId, buffer);
250
+ }
251
+ if (buffer.flushed) {
252
+ buffer.texts = [];
253
+ buffer.firstAt = Date.now();
254
+ buffer.flushed = false;
255
+ }
256
+ buffer.texts.push(text);
257
+ if (buffer.timer !== undefined)
258
+ clearTimeout(buffer.timer);
259
+ const elapsed = Date.now() - buffer.firstAt;
260
+ if (elapsed >= maxWait) {
261
+ await this.flushBuffer(sessionId, false);
262
+ return;
263
+ }
264
+ buffer.timer = setTimeout(() => { void this.flushBuffer(sessionId, false); }, window);
265
+ }
266
+ async flushBuffer(sessionId, final) {
267
+ const buffer = this.buffers.get(sessionId);
268
+ if (buffer === undefined)
269
+ return;
270
+ if (buffer.timer !== undefined) {
271
+ clearTimeout(buffer.timer);
272
+ buffer.timer = undefined;
273
+ }
274
+ if (buffer.texts.length === 0)
275
+ return;
276
+ const text = buffer.texts.join('\n\n');
277
+ buffer.texts = [];
278
+ buffer.flushed = true;
279
+ await this.sendStatic(sessionId, text);
280
+ if (!final)
281
+ return;
282
+ }
283
+ /** Send static text chunks with passive-anchor accounting. */
284
+ async sendStatic(sessionId, text) {
285
+ const target = this.targetOf(sessionId);
286
+ this.deps.log.info('QQ outbound: sendStatic %d chars to %s session=%s', text.length, target.kind, sessionId);
287
+ const limit = this.deps.config.textChunkLimit ?? 4_000;
288
+ const chunks = chunkText(text, limit);
289
+ for (const chunk of chunks) {
290
+ const record = this.deps.routes.get(sessionId);
291
+ const passive = record !== undefined
292
+ ? this.deps.routes.consumePassive(sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, this.deps.config.replyPassiveLimit ?? 4)
293
+ : undefined;
294
+ try {
295
+ await this.deps.api.sendText(target, chunk, passive);
296
+ }
297
+ catch (error) {
298
+ this.deps.log.error('QQ reply send failed for %s: %o', sessionId, error);
299
+ return;
300
+ }
301
+ }
302
+ }
303
+ /** Flush everything on shutdown so pending merged texts are not lost. */
304
+ async dispose() {
305
+ for (const sessionId of [...this.buffers.keys()]) {
306
+ await this.flushBuffer(sessionId, true).catch(() => undefined);
307
+ }
308
+ this.buffers.clear();
309
+ this.streams.clear();
310
+ }
311
+ // ── Approval answerer (registered per QQ agent scope) ─────────────────────
312
+ /**
313
+ * Register the QQ inline-keyboard approval answerer on one agent's scoped
314
+ * context. Mirrors openclaw's three-button keyboard; "always allow" is
315
+ * remembered in the persistent store and auto-answers future asks for the
316
+ * same tool in the same QQ session.
317
+ */
318
+ registerApprovalAnswerer(agentCtx, sessionId) {
319
+ if (this.deps.config.approval === false)
320
+ return;
321
+ const onApproval = agentCtx.on;
322
+ onApproval('approval/request', async (req, next) => {
323
+ if (req.agent.id !== sessionId)
324
+ return next();
325
+ if (this.deps.alwaysAllow.allows(sessionId, req.toolName))
326
+ return 'allowed-once';
327
+ const token = `${sessionId}:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
328
+ const decision = new Promise((resolve) => {
329
+ this.pendingApprovals.set(token, {
330
+ resolve: (choice) => resolve(choice === 'deny' ? 'rejected' : choice === 'allow-always' ? 'allow-always' : 'allowed-once'),
331
+ });
332
+ });
333
+ const target = this.targetOf(sessionId);
334
+ const anchor = this.deps.routes.get(sessionId);
335
+ const passive = anchor !== undefined
336
+ ? this.deps.routes.consumePassive(sessionId, 30 * 60 * 1000, 8)
337
+ : undefined;
338
+ try {
339
+ await this.deps.api.sendKeyboard(target, `⚠️ 需要审批:${req.toolName}\n${req.reason ?? '该操作需要你的确认。'}`, [
340
+ { id: 'allow', label: '✅ 允许一次', visitedLabel: '已允许', style: 1, data: `dshqq:${token}:allow-once` },
341
+ { id: 'always', label: '⭐ 始终允许', visitedLabel: '已始终允许', style: 1, data: `dshqq:${token}:allow-always` },
342
+ { id: 'deny', label: '❌ 拒绝', visitedLabel: '已拒绝', style: 0, data: `dshqq:${token}:deny` },
343
+ ], passive);
344
+ }
345
+ catch (error) {
346
+ this.deps.log.warn('approval keyboard send failed: %o', error);
347
+ this.pendingApprovals.delete(token);
348
+ return next();
349
+ }
350
+ const timeoutMs = this.deps.config.approvalTimeoutMs ?? 300_000;
351
+ const outcome = await this.raceDecision(decision, req, timeoutMs, token);
352
+ if (outcome === 'allow-always') {
353
+ this.deps.alwaysAllow.add(sessionId, req.toolName);
354
+ return 'allowed-once';
355
+ }
356
+ return outcome;
357
+ });
358
+ }
359
+ async raceDecision(decision, req, timeoutMs, token) {
360
+ const timeout = new Promise((resolve) => {
361
+ setTimeout(() => resolve('rejected'), timeoutMs);
362
+ });
363
+ const aborted = new Promise((resolve) => {
364
+ req.signal?.addEventListener('abort', () => resolve('cancelled'), { once: true });
365
+ });
366
+ try {
367
+ const outcome = await Promise.race([decision, timeout, aborted]);
368
+ this.pendingApprovals.delete(token);
369
+ return outcome;
370
+ }
371
+ catch (error) {
372
+ this.deps.log.warn('approval decision failed: %o', error);
373
+ this.pendingApprovals.delete(token);
374
+ return 'rejected';
375
+ }
376
+ }
377
+ /** Resolve a pending approval from an INTERACTION_CREATE button press. */
378
+ handleApprovalCallback(buttonData) {
379
+ const match = /^dshqq:(.+):(allow-once|allow-always|deny)$/.exec(buttonData);
380
+ if (match === null)
381
+ return undefined;
382
+ const token = match[1];
383
+ const decision = match[2];
384
+ const pending = this.pendingApprovals.get(token);
385
+ if (pending === undefined)
386
+ return undefined;
387
+ this.pendingApprovals.delete(token);
388
+ pending.resolve(decision);
389
+ return decision;
390
+ }
391
+ }
392
+ //# sourceMappingURL=outbound.js.map