pygmalion 0.1.5 → 0.1.7

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/src/tools.js CHANGED
@@ -1,511 +1,904 @@
1
- import { targetOfSession, SESSION_PREFIX } from './inbound.js';
2
- import { readdir, readFile } from 'node:fs/promises';
3
- import { existsSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readLifeManifest, snapshotLifeScript } from './agent-life.js';
6
- import { sessionFileFor } from './active-session.js';
7
- import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
8
-
9
- const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
10
- const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
11
- const VIDEO_EXTS = new Set(['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']);
12
- export function inferMediaKind(source, mimeHint) {
13
- if (mimeHint !== undefined) {
14
- if (mimeHint.startsWith('image/'))
15
- return 'image';
16
- if (mimeHint.startsWith('audio/'))
17
- return 'voice';
18
- if (mimeHint.startsWith('video/'))
19
- return 'video';
20
- if (mimeHint === 'application/octet-stream' || mimeHint.startsWith('text/'))
21
- return 'file';
22
- }
23
- const ext = source.slice(source.lastIndexOf('.')).toLowerCase();
24
- if (IMAGE_EXTS.has(ext))
25
- return 'image';
26
- if (VOICE_EXTS.has(ext))
27
- return 'voice';
28
- if (VIDEO_EXTS.has(ext))
29
- return 'video';
30
- return 'file';
31
- }
32
-
33
- /** life_run 结果的模型侧渲染:回显启动的脚本(runId/pid)或终止结果。 */
34
- function renderLifeRun(value) {
35
- const v = value;
36
- if (!v?.ok) return `life_run 失败: ${v?.error ?? '?'}`;
37
- if (v.stopped) return `已终止生活脚本 runId=${v.stopped}`;
38
- const lines = [`生活脚本已启动:${v.script ?? ''}(runId=${v.runId}, pid=${v.pid})`];
39
- lines.push('脚本在后台运行,由脚本自己决定何时结束(可长驻循环);插件只监管展示、不限制运行。输出进 life/.logs/,状态见管理页。');
40
- if (v.error) lines.push(`注意: ${v.error}`);
41
- return lines.join('\n');
42
- }
43
-
44
- /**
45
- * 会话工具上下文:一次工具执行需要的全部依赖。由各注册路径构造:
46
- * - own 层(registerQQTools/registerDirectorTools):注册时静态捕获;
47
- * - standing 层(registerStandingTools):执行时按 exec.agent.id 从宿主服务动态解析。
48
- * @typedef {{ sessionId: string, api: object, routes?: object,
49
- * target: () => any, roleId?: string, httpApiToken?: string, httpApiPath?: string,
50
- * persona?: object, log?: object, workspaceOf?: () => Promise<string> }} ToolCtx
51
- */
52
-
53
- /**
54
- * QQ 媒体/API 工具定义(qq_send_media / qq_api)。resolveCtx(args, exec) 返回
55
- * 本次执行的 {@link ToolCtx};同一套定义既用于 own 层(静态闭包)也用于
56
- * standing 层(按 exec.agent.id 动态解析)。
57
- */
58
- export function buildQQToolDefs(resolveCtx) {
59
- return [
60
- {
61
- name: 'qq_send_media',
62
- description: 'Send an image, voice, video, or file message to the current QQ chat. '
63
- + 'Accepts an https URL, a data: URL, or an absolute local file path '
64
- + '(files larger than 10MB upload through the chunked pipeline automatically). '
65
- + 'Use this instead of pasting image URLs as text when the user asks for a media message.',
66
- parameters: {
67
- type: 'object',
68
- additionalProperties: false,
69
- properties: {
70
- source: { type: 'string', description: 'https URL, data: URL, or absolute local file path of the media.' },
71
- kind: { type: 'string', enum: ['image', 'voice', 'video', 'file'], description: 'Media kind; inferred from the extension when omitted.' },
72
- text: { type: 'string', description: 'Optional caption sent alongside the media.' },
73
- },
74
- required: ['source'],
75
- },
76
- output: {
77
- schema: {
78
- type: 'object',
79
- additionalProperties: false,
80
- properties: {
81
- sent: { type: 'boolean' },
82
- kind: { type: 'string' },
83
- error: { type: 'string' },
84
- },
85
- required: ['sent', 'kind'],
86
- },
87
- render: (_args, value) => {
88
- const record = value;
89
- const text = record?.sent === true
90
- ? `已发送${record.kind ?? '媒体'}消息`
91
- : `媒体发送失败: ${record?.error ?? 'unknown error'}`;
92
- return [{ type: 'text', text }];
93
- },
94
- },
95
- timeoutMs: 300_000,
96
- async execute(args, exec) {
97
- const c = await resolveCtx(args, exec);
98
- const input = args;
99
- const kind = input.kind ?? inferMediaKind(input.source);
100
- try {
101
- await c.api.sendMedia(c.target(), kind, input.source, { text: input.text });
102
- return { sent: true, kind };
103
- }
104
- catch (error) {
105
- return { sent: false, kind, error: error instanceof Error ? error.message : String(error) };
106
- }
107
- },
108
- },
109
- {
110
- name: 'qq_api',
111
- description: 'Proxy any QQ Open Platform REST API call (guild/channel management, '
112
- + 'announcements, schedules, group info, member queries) with automatic '
113
- + 'access-token injection. Base URL is already configured; pass only the path, '
114
- + 'e.g. "/users/@me/guilds". Query values must be strings.',
115
- parameters: {
116
- type: 'object',
117
- additionalProperties: false,
118
- properties: {
119
- method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
120
- path: { type: 'string', description: 'API path starting with "/". Must not contain ".." or "//".' },
121
- body: { type: 'object', description: 'JSON body for POST/PUT/PATCH.' },
122
- query: { type: 'object', additionalProperties: { type: 'string' }, description: 'URL query parameters.' },
123
- },
124
- required: ['method', 'path'],
125
- },
126
- output: {
127
- // Unconstrained lossless JSON (empty annotation-only node) — DSH rejects
128
- // `{ type: 'json' }` as an unsupported JSON schema type.
129
- schema: {},
130
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
131
- },
132
- timeoutMs: 60_000,
133
- async execute(args, exec) {
134
- const c = await resolveCtx(args, exec);
135
- const input = args;
136
- if (!input.path.startsWith('/') || input.path.includes('..') || input.path.includes('//')) {
137
- throw new Error(`invalid path: ${input.path}`);
138
- }
139
- return await c.api.request(input.method, input.path, input.body, { query: input.query });
140
- },
141
- },
142
- ];
143
- }
144
- /** Session-id guard helper shared by index.ts wiring. */
145
- export function isQQSession(sessionId) {
146
- return sessionId.startsWith(`${SESSION_PREFIX}:`);
147
- }
148
-
149
- /**
150
- * Pygmalion 导演工具定义(director_send / recollect / life_run)。resolveCtx(args, exec)
151
- * 返回本次执行的 {@link ToolCtx};同一套定义既用于 own 层也用于 standing 层。
152
- */
153
- export function buildDirectorToolDefs(resolveCtx) {
154
- return [
155
- // director_send:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
156
- {
157
- name: 'director_send',
158
- description: '向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。你必须决定“发几条、每条内容”:'
159
- + 'messages 为一次下发的 1~N 条消息,会逐条发送以模拟真实打字节奏(写“小作文”可拆成多条)。'
160
- + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
161
- + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你继续这段对话;'
162
- + '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
163
- + '这轮聊完之后你将一直静默等待用户。reawake 的分钟数应当根据当下的具体情景灵活决定,'
164
- + '不要套用固定的区间:如果你们正聊到一半、话题还没有结束,或者你并不想结束这次聊天,'
165
- + '就填一个较短的间隔,比如 3 到 10 分钟;如果你们约定了某个具体的时刻再继续,比如'
166
- + '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
167
- + '自然地把话题搁一搁,填一个适中的间隔即可。'
168
- + 'messages 为空数组时可只安排 reawake 而本次不发。'
169
- + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
170
- + '如果你决定此刻不打扰对方,就不要调用本工具。',
171
- parameters: {
172
- type: 'object',
173
- additionalProperties: false,
174
- properties: {
175
- messages: {
176
- type: 'array',
177
- items: { type: 'string' },
178
- description: '要逐条发送的聊天消息列表;空数组或省略 = 不发送(沉默)。',
179
- },
180
- reawake: {
181
- oneOf: [{ type: 'number' }, { type: 'string' }],
182
- description: '建议默认携带。具体的分钟数根据当下的情景决定:如果话题还没有结束,'
183
- + '填一个较短的间隔,比如 3 到 10 分钟;如果约定了某个具体的时刻再继续,就填到那个时刻的分钟数,'
184
- + '比如约好中午再聊、距离中午还有 3 个小时,就填 180;平时自然搁置则填一个适中的间隔。'
185
- + '填正数会登记等待队列;明确决定这轮不再续聊时才写 "none" 或省略。',
186
- },
187
- reason: {
188
- type: 'string',
189
- description: '可选:reawake 到期时唤醒你的缘由(你想继续说的话/想确认的事)。',
190
- },
191
- },
192
- },
193
- output: {
194
- schema: {
195
- type: 'object',
196
- additionalProperties: false,
197
- properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
198
- required: ['ok', 'sent'],
199
- },
200
- render: (_args, value) => [
201
- { type: 'text', text: value.ok
202
- ? `已发送 ${value.sent} 条消息${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
203
- : `发送失败: ${value.error ?? '?'}` },
204
- ],
205
- },
206
- timeoutMs: 60_000,
207
- async execute(args, exec) {
208
- const c = await resolveCtx(args, exec);
209
- const raw = Array.isArray(args?.messages) ? args.messages : [];
210
- const messages = raw.map((s) => String(s ?? '').trim()).filter((s) => s.length > 0);
211
- const sent = [];
212
- if (messages.length > 0) {
213
- const record = c.routes?.get(c.sessionId);
214
- const passive = record
215
- ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
216
- : undefined;
217
- for (const msg of messages) {
218
- try {
219
- await c.api.sendText(c.target(), msg, passive);
220
- sent.push(msg);
221
- }
222
- catch (error) {
223
- return {
224
- ok: false, sent: sent.length,
225
- error: error instanceof Error ? error.message : String(error),
226
- };
227
- }
228
- }
229
- // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
230
- // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
231
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
232
- const workspace = c.workspaceOf
233
- ? await c.workspaceOf()
234
- : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
235
- if (workspace && c.sessionId) {
236
- const file = sessionFileFor({ sessionId: c.sessionId, workspace });
237
- // 会话文件不存在则无内容可提取(测试/调试 stub 路径跳过,避免挂空定时器)。
238
- if (existsSync(file)) {
239
- const charLabel = c.roleId && c.persona ? await charLabelOf(c.persona, c.roleId) : '角色';
240
- setTimeout(() => {
241
- void refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log: c.log })
242
- .catch((error) => c.log?.warn?.('pygmalion: 刷新原始记录失败: %o', error));
243
- }, 3000);
244
- }
245
- }
246
- }
247
- }
248
- // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
249
- const ra = args?.reawake;
250
- if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
251
- return { ok: true, sent: sent.length };
252
- const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
253
- if (Number.isFinite(minutes) && minutes > 0) {
254
- const rw = c.roleId && c.persona?.scheduleRewake
255
- ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '')
256
- : { ok: false, atMs: 0, error: '无角色上下文' };
257
- if (!rw.ok)
258
- return { ok: false, sent: sent.length, error: `reawake 安排失败: ${rw.error ?? '?'}` };
259
- return { ok: true, sent: sent.length, reawake: rw.atMs };
260
- }
261
- return { ok: true, sent: sent.length };
262
- },
263
- },
264
- // recollect:按需回忆(只在需要回忆/找话题时调用)
265
- {
266
- name: 'recollect',
267
- description: '按需回忆记忆:读取已归档的聊天索引(话题层 topics/ + 日期层 + 特殊记忆 关于TA.md)'
268
- + '用于引用过去的事、延续话题或找话题。默认返回特殊记忆 + 最近话题索引 + 最近几个日期的索引速查;'
269
- + '可指定 date=YYYY-MM-DD 读某天,或用 topic 关键字过滤。只在需要回忆时才调用;'
270
- + '日常不要读写记忆文件(归档由系统自动完成,特殊记忆可直接编辑 关于TA.md)。',
271
- parameters: {
272
- type: 'object',
273
- additionalProperties: false,
274
- properties: {
275
- date: { type: 'string', description: '可选,YYYY-MM-DD:只读那一天的索引/原文。' },
276
- topic: { type: 'string', description: '可选,要回忆的关键字(在特殊记忆/话题/索引/原文里检索)。' },
277
- limit: { type: 'number', description: '可选,最多读取最近多少个日期的索引(默认 3,上限 10)。' },
278
- },
279
- },
280
- output: {
281
- schema: {
282
- type: 'object',
283
- additionalProperties: false,
284
- properties: { found: { type: 'boolean' }, text: { type: 'string' } },
285
- required: ['found', 'text'],
286
- },
287
- render: (_args, value) => [
288
- { type: 'text', text: value.found ? `[回忆]\n${String(value.text).slice(0, 4000)}` : '(记忆中没有相关内容)' },
289
- ],
290
- },
291
- timeoutMs: 20_000,
292
- async execute(args, exec) {
293
- const c = await resolveCtx(args, exec);
294
- const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
295
- if (!ws) return { found: false, text: '' };
296
- const mem = join(ws, 'memory');
297
- const out = [];
298
- // 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
299
- try {
300
- const ta = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
301
- if (ta && ta !== '(空白,等待你记录对 TA 的了解)')
302
- out.push(`== 关于TA(特殊记忆)==\n${ta.slice(0, 2000)}`);
303
- } catch { /* 尚无特殊记忆 */ }
304
- // 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
305
- try {
306
- const subs = (await readdir(join(mem, 'topics'))).filter((n) => !n.startsWith('.')).sort().reverse();
307
- for (const name of subs.slice(0, 20)) {
308
- try {
309
- const ti = await readFile(join(mem, 'topics', name, '索引.md'), 'utf8');
310
- out.push(`== 话题 ${name} ==\n${ti.slice(0, 1200)}`);
311
- } catch { /* 该话题无索引 */ }
312
- }
313
- } catch { /* 无话题层 */ }
314
- // 日期层:索引(默认最近 N 天;指定日期则附当日原文片段)
315
- let dates = [];
316
- try { dates = (await readdir(mem)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n)).sort().reverse(); } catch { /* no memory yet */ }
317
- if (dates.length) {
318
- const limit = Math.min(Math.max(Number(args?.limit) || 3, 1), 10);
319
- const pick = args?.date ? [String(args.date)] : dates.slice(0, limit);
320
- for (const d of pick) {
321
- const idx = join(mem, d, '索引.md');
322
- const raw = join(mem, d, '原始记录.md');
323
- try {
324
- let t = `== ${d} 索引 ==\n` + await readFile(idx, 'utf8');
325
- if (args?.date && args.date === d) {
326
- try { t += `\n== ${d} 原文(片段) ==\n` + (await readFile(raw, 'utf8')).slice(0, 2000); } catch { /* 无原文 */ }
327
- }
328
- out.push(t);
329
- } catch { /* 该日无索引 */ }
330
- }
331
- }
332
- let text = out.join('\n\n');
333
- if (args?.topic) {
334
- const q = String(args.topic).toLowerCase();
335
- const filtered = text.split('\n').filter((l) => l.toLowerCase().includes(q));
336
- text = filtered.length ? filtered.join('\n') : text;
337
- }
338
- return text.trim() ? { found: true, text: text.trim().slice(0, 6000) } : { found: false, text: '' };
339
- },
340
- },
341
- // life_run:在插件监管下启动/终止角色生活脚本(dsh 全权决定运行,插件只监管展示)
342
- {
343
- name: 'life_run',
344
- description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
345
- + '脚本是“角色生活的程序化模拟器”:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
346
- + '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
347
- + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“ta 很久没回就去找 ta”。'
348
- + '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
349
- + '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
350
- + '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
351
- + '要终止用 stop=<runId>。'
352
- + '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
353
- + '突发小事件、想 ta 的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
354
- + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
355
- + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
356
- + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
357
- + '(可以选择沉默)——没有被唤醒的事件就失去了意义。'
358
- + '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
359
- + '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
360
- + '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
361
- + '注意:wake() 是异步的——一次性脚本务必 await wake(...);长驻循环脚本里调用后要'
362
- + '保持进程存活,否则请求可能随进程退出(如 process.exit)而丢失。'
363
- + '注入环境变量:PYG_QQ / PYG_WORKSPACE / PYG_DATA_ROOT / PYG_STATE_FILE / '
364
- + 'PYG_LAST_USER_AT(最后用户活动时间 epoch ms)/ PYG_TOKEN / PYG_BASE / '
365
- + 'PYG_HTTP_API_PATH / PYG_OPENID(wake() 的唤醒目标)。',
366
- parameters: {
367
- type: 'object',
368
- additionalProperties: false,
369
- properties: {
370
- script: { type: 'string', description: 'life/ 下要启动的脚本文件名(如 script-春天.mjs);省略则启动约定的 main.*/index.*。' },
371
- reason: { type: 'string', description: '可选:这次启动/终止的缘由(写进运行日志)。' },
372
- stop: { type: 'string', description: '可选:要终止的运行中脚本 runId(提供时不再启动新脚本)。' },
373
- },
374
- },
375
- output: {
376
- schema: {
377
- type: 'object',
378
- additionalProperties: false,
379
- properties: {
380
- ok: { type: 'boolean' },
381
- runId: { type: 'string' },
382
- pid: { type: 'number' },
383
- startedAt: { type: 'number' },
384
- script: { type: 'string' },
385
- stopped: { type: 'string' },
386
- error: { type: 'string' },
387
- },
388
- required: ['ok'],
389
- },
390
- render: (_args, value) => [{ type: 'text', text: renderLifeRun(value) }],
391
- },
392
- timeoutMs: 60_000,
393
- async execute(args, exec) {
394
- const c = await resolveCtx(args, exec);
395
- const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
396
- if (!ws) return { ok: false, error: '无角色工作区上下文' };
397
-
398
- // stop 模式:终止一个运行中脚本(不启动新脚本)
399
- if (typeof args?.stop === 'string' && args.stop.trim()) {
400
- const res = await stopLifeScript(args.stop.trim());
401
- return res.ok ? { ok: true, stopped: res.runId } : { ok: false, error: res.error || '终止失败' };
402
- }
403
-
404
- const scripts = await listLifeScripts(ws);
405
- const given = typeof args?.script === 'string' ? String(args.script).trim() : '';
406
- let script;
407
- if (given) {
408
- const p = join(ws, 'life', given);
409
- if (!existsSync(p))
410
- return { ok: false, error: `life/${given} 不存在(当前脚本:${scripts.join(', ') || '无'})` };
411
- script = p;
412
- } else {
413
- const found = await findLifeScript(ws);
414
- if (!found)
415
- return { ok: false, error: scripts.length
416
- ? `life/ 有脚本但无约定主脚本(${scripts.join(', ')}):请用 script=<文件名> 指定要启动哪个。`
417
- : 'life/ 下还没有任何脚本——先新建一个(新文件,勿覆盖已有文件)再用 life_run 启动。' };
418
- script = found;
419
- }
420
- try {
421
- await snapshotLifeScript({ workspace: ws, script, manifest: await readLifeManifest(ws) });
422
- } catch { /* 快照失败不阻塞启动 */ }
423
- const lastUserAt = c.routes?.get?.(c.sessionId)?.lastMsgAt;
424
- const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
425
- const res = await startLifeScript(script, {
426
- qq: c.roleId ?? '',
427
- workspace: ws,
428
- dataRoot: c.persona?.dataRoot?.(),
429
- stateFile: c.roleId && c.persona?.roleDir ? join(c.persona.roleDir(c.roleId), 'state.json') : undefined,
430
- lastUserAt,
431
- token: c.httpApiToken,
432
- httpApiPath: c.httpApiPath,
433
- openid: role?.binding?.openid,
434
- });
435
- return res.ok
436
- ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
437
- : { ok: false, error: res.error || '启动失败' };
438
- },
439
- },
440
- ];
441
- }
442
-
443
- /** own 层注册 QQ 工具(setup 兜底路径,签名与旧版一致)。 */
444
- export function registerQQTools(agentCtx, sessionId, api, routeTarget) {
445
- const tools = agentCtx.tools;
446
- if (tools === undefined)
447
- return;
448
- const target = () => routeTarget() ?? targetOfSession(sessionId);
449
- const resolveCtx = async (_args, exec) => ({
450
- sessionId: exec?.agent?.id ?? sessionId,
451
- api, routes: undefined, target,
452
- roleId: undefined, httpApiToken: undefined, httpApiPath: undefined, persona: undefined, log: undefined, workspaceOf: undefined,
453
- });
454
- for (const def of buildQQToolDefs(resolveCtx))
455
- tools.register(def);
456
- }
457
-
458
- /**
459
- * Pygmalion 导演发送工具:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
460
- * 注册进会话 own 层(setup 兜底路径,签名与旧版一致)。
461
- */
462
- export function registerDirectorTools(agentCtx, sessionId, deps) {
463
- const tools = agentCtx.tools;
464
- if (tools === undefined)
465
- return false;
466
- const target = () => deps.target?.() ?? targetOfSession(sessionId);
467
- const resolveCtx = async (_args, exec) => ({
468
- sessionId: exec?.agent?.id ?? sessionId,
469
- api: deps.api, routes: deps.routes, target,
470
- roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
471
- persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
472
- });
473
- for (const def of buildDirectorToolDefs(resolveCtx))
474
- tools.register(def);
475
- return true;
476
- }
477
-
478
- /**
479
- * 把 pygmalion 全套工具注册进 standing 层(由 preset 桥插件经宿主服务调用)。
480
- * 工具定义每进程一份;执行时按 exec.agent.id 从 depsFor(sessionId) 动态解析每会话依赖,
481
- * 因此 resume 恢复会话后 dispatch 依然可达(与 preset 内 fs/bash 工具同一层)。
482
- * @param ctx 桥插件上下文(standing 层 scope 上下文)
483
- * @param depsFor 会话依赖解析函数:sessionId → { api, routes, target, roleId, httpApiToken, persona, log, workspaceOf }
484
- * (可能为 async:宿主服务可在未命中时按 sessionId 惰性构造依赖)
485
- * @returns 是否完成注册
486
- */
487
- export function registerStandingTools(ctx, depsFor) {
488
- const tools = ctx.tools;
489
- if (tools === undefined)
490
- return false;
491
- const resolveCtx = async (_args, exec) => {
492
- const sessionId = exec?.agent?.id;
493
- if (!sessionId)
494
- throw new Error('pygmalion: 工具调用缺少会话上下文(exec.agent.id 为空)');
495
- const deps = await depsFor(sessionId);
496
- if (deps === undefined)
497
- throw new Error(`pygmalion: 会话 ${sessionId} 的 pygmalion 上下文未注册(setup 未运行?该 agent 并非由 pygmalion 启动?)`);
498
- return {
499
- sessionId,
500
- api: deps.api, routes: deps.routes,
501
- target: () => deps.target?.() ?? targetOfSession(sessionId),
502
- roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
503
- persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
504
- };
505
- };
506
- for (const def of buildQQToolDefs(resolveCtx))
507
- tools.register(def);
508
- for (const def of buildDirectorToolDefs(resolveCtx))
509
- tools.register(def);
510
- return true;
511
- }
1
+ import { targetOfSession, SESSION_PREFIX } from './inbound.js';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readLifeManifest, snapshotLifeScript } from './agent-life.js';
6
+ import { sessionFileFor } from './active-session.js';
7
+ import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
8
+ import { saveMeme, findMemes, memeFileFor, updateMeme, recordMemeUsed, downloadPageImagesToCollectDir } from './memebox.js';
9
+ import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
10
+
11
+ const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
12
+ const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
13
+
14
+ /** dsh 工具输出要求无损 JSON(拒绝 undefined/NaN/非有限数);返回前剥掉 undefined 字段。 */
15
+ function noUndefined(obj) {
16
+ const out = {};
17
+ for (const [k, v] of Object.entries(obj)) if (v !== undefined) out[k] = v;
18
+ return out;
19
+ }
20
+ const VIDEO_EXTS = new Set(['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']);
21
+ export function inferMediaKind(source, mimeHint) {
22
+ if (mimeHint !== undefined) {
23
+ if (mimeHint.startsWith('image/'))
24
+ return 'image';
25
+ if (mimeHint.startsWith('audio/'))
26
+ return 'voice';
27
+ if (mimeHint.startsWith('video/'))
28
+ return 'video';
29
+ if (mimeHint === 'application/octet-stream' || mimeHint.startsWith('text/'))
30
+ return 'file';
31
+ }
32
+ const ext = source.slice(source.lastIndexOf('.')).toLowerCase();
33
+ if (IMAGE_EXTS.has(ext))
34
+ return 'image';
35
+ if (VOICE_EXTS.has(ext))
36
+ return 'voice';
37
+ if (VIDEO_EXTS.has(ext))
38
+ return 'video';
39
+ return 'file';
40
+ }
41
+
42
+ /** life_run 结果的模型侧渲染:回显启动的脚本(runId/pid)或终止结果。 */
43
+ function renderLifeRun(value) {
44
+ const v = value;
45
+ if (!v?.ok) return `life_run 失败: ${v?.error ?? '?'}`;
46
+ if (v.stopped) return `已终止生活脚本 runId=${v.stopped}`;
47
+ const lines = [`生活脚本已启动:${v.script ?? ''}(runId=${v.runId}, pid=${v.pid})`];
48
+ lines.push('脚本在后台运行,由脚本自己决定何时结束(可长驻循环);插件只监管展示、不限制运行。输出进 life/.logs/,状态见管理页。');
49
+ if (v.error) lines.push(`注意: ${v.error}`);
50
+ return lines.join('\n');
51
+ }
52
+
53
+ /**
54
+ * 会话工具上下文:一次工具执行需要的全部依赖。由各注册路径构造:
55
+ * - own 层(registerQQTools/registerDirectorTools):注册时静态捕获;
56
+ * - standing 层(registerStandingTools):执行时按 exec.agent.id 从宿主服务动态解析。
57
+ * @typedef {{ sessionId: string, api: object, routes?: object,
58
+ * target: () => any, roleId?: string, httpApiToken?: string, httpApiPath?: string,
59
+ * persona?: object, log?: object, workspaceOf?: () => Promise<string>,
60
+ * subagents?: object, llm?: object }} ToolCtx
61
+ */
62
+
63
+ /**
64
+ * QQ 媒体/API 工具定义(qq_send_media / qq_api)。resolveCtx(args, exec) 返回
65
+ * 本次执行的 {@link ToolCtx};同一套定义既用于 own 层(静态闭包)也用于
66
+ * standing 层(按 exec.agent.id 动态解析)。
67
+ */
68
+ export function buildQQToolDefs(resolveCtx) {
69
+ return [
70
+ {
71
+ name: 'qq_send_media',
72
+ description: 'Send an image, voice, video, or file message to the current QQ chat. '
73
+ + 'Accepts an https URL, a data: URL, or an absolute local file path '
74
+ + '(files larger than 10MB upload through the chunked pipeline automatically). '
75
+ + 'Use this instead of pasting image URLs as text when the user asks for a media message.',
76
+ parameters: {
77
+ type: 'object',
78
+ additionalProperties: false,
79
+ properties: {
80
+ source: { type: 'string', description: 'https URL, data: URL, or absolute local file path of the media.' },
81
+ kind: { type: 'string', enum: ['image', 'voice', 'video', 'file'], description: 'Media kind; inferred from the extension when omitted.' },
82
+ text: { type: 'string', description: 'Optional caption sent alongside the media.' },
83
+ },
84
+ required: ['source'],
85
+ },
86
+ output: {
87
+ schema: {
88
+ type: 'object',
89
+ additionalProperties: false,
90
+ properties: {
91
+ sent: { type: 'boolean' },
92
+ kind: { type: 'string' },
93
+ error: { type: 'string' },
94
+ },
95
+ required: ['sent', 'kind'],
96
+ },
97
+ render: (_args, value) => {
98
+ const record = value;
99
+ const text = record?.sent === true
100
+ ? `已发送${record.kind ?? '媒体'}消息`
101
+ : `媒体发送失败: ${record?.error ?? 'unknown error'}`;
102
+ return [{ type: 'text', text }];
103
+ },
104
+ },
105
+ timeoutMs: 300_000,
106
+ async execute(args, exec) {
107
+ const c = await resolveCtx(args, exec);
108
+ const input = args;
109
+ const kind = input.kind ?? inferMediaKind(input.source);
110
+ try {
111
+ await c.api.sendMedia(c.target(), kind, input.source, { text: input.text });
112
+ return { sent: true, kind };
113
+ }
114
+ catch (error) {
115
+ return { sent: false, kind, error: error instanceof Error ? error.message : String(error) };
116
+ }
117
+ },
118
+ },
119
+ {
120
+ name: 'qq_api',
121
+ description: 'Proxy any QQ Open Platform REST API call (guild/channel management, '
122
+ + 'announcements, schedules, group info, member queries) with automatic '
123
+ + 'access-token injection. Base URL is already configured; pass only the path, '
124
+ + 'e.g. "/users/@me/guilds". Query values must be strings.',
125
+ parameters: {
126
+ type: 'object',
127
+ additionalProperties: false,
128
+ properties: {
129
+ method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
130
+ path: { type: 'string', description: 'API path starting with "/". Must not contain ".." or "//".' },
131
+ body: { type: 'object', description: 'JSON body for POST/PUT/PATCH.' },
132
+ query: { type: 'object', additionalProperties: { type: 'string' }, description: 'URL query parameters.' },
133
+ },
134
+ required: ['method', 'path'],
135
+ },
136
+ output: {
137
+ // Unconstrained lossless JSON (empty annotation-only node) — DSH rejects
138
+ // `{ type: 'json' }` as an unsupported JSON schema type.
139
+ schema: {},
140
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
141
+ },
142
+ timeoutMs: 60_000,
143
+ async execute(args, exec) {
144
+ const c = await resolveCtx(args, exec);
145
+ const input = args;
146
+ if (!input.path.startsWith('/') || input.path.includes('..') || input.path.includes('//')) {
147
+ throw new Error(`invalid path: ${input.path}`);
148
+ }
149
+ return await c.api.request(input.method, input.path, input.body, { query: input.query });
150
+ },
151
+ },
152
+ ];
153
+ }
154
+ /** Session-id guard helper shared by index.ts wiring. */
155
+ export function isQQSession(sessionId) {
156
+ return sessionId.startsWith(`${SESSION_PREFIX}:`);
157
+ }
158
+
159
+ /**
160
+ * Pygmalion 导演工具定义(director_send / recollect / life_run)。resolveCtx(args, exec)
161
+ * 返回本次执行的 {@link ToolCtx};同一套定义既用于 own 层也用于 standing 层。
162
+ */
163
+ export function buildDirectorToolDefs(resolveCtx) {
164
+ return [
165
+ // director_send:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
166
+ {
167
+ name: 'director_send',
168
+ description: '向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。你必须决定“发几条、每条内容”:'
169
+ + 'messages 为一次下发的 1~N 条消息,会逐条发送以模拟真实打字节奏(写“小作文”可拆成多条)。'
170
+ + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
171
+ + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你继续这段对话;'
172
+ + '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
173
+ + '这轮聊完之后你将一直静默等待用户。reawake 的分钟数应当根据当下的具体情景灵活决定,'
174
+ + '不要套用固定的区间:如果你们正聊到一半、话题还没有结束,或者你并不想结束这次聊天,'
175
+ + '就填一个较短的间隔,比如 3 到 10 分钟;如果你们约定了某个具体的时刻再继续,比如'
176
+ + '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
177
+ + '自然地把话题搁一搁,填一个适中的间隔即可。'
178
+ + 'messages 为空数组时可只安排 reawake 而本次不发。'
179
+ + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
180
+ + '如果你决定此刻不打扰对方,就不要调用本工具。',
181
+ parameters: {
182
+ type: 'object',
183
+ additionalProperties: false,
184
+ properties: {
185
+ messages: {
186
+ type: 'array',
187
+ items: { type: 'string' },
188
+ description: '要逐条发送的聊天消息列表;空数组或省略 = 不发送(沉默)。',
189
+ },
190
+ reawake: {
191
+ oneOf: [{ type: 'number' }, { type: 'string' }],
192
+ description: '建议默认携带。具体的分钟数根据当下的情景决定:如果话题还没有结束,'
193
+ + '填一个较短的间隔,比如 3 到 10 分钟;如果约定了某个具体的时刻再继续,就填到那个时刻的分钟数,'
194
+ + '比如约好中午再聊、距离中午还有 3 个小时,就填 180;平时自然搁置则填一个适中的间隔。'
195
+ + '填正数会登记等待队列;明确决定这轮不再续聊时才写 "none" 或省略。',
196
+ },
197
+ reason: {
198
+ type: 'string',
199
+ description: '可选:reawake 到期时唤醒你的缘由(你想继续说的话/想确认的事)。',
200
+ },
201
+ },
202
+ },
203
+ output: {
204
+ schema: {
205
+ type: 'object',
206
+ additionalProperties: false,
207
+ properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
208
+ required: ['ok', 'sent'],
209
+ },
210
+ render: (_args, value) => [
211
+ { type: 'text', text: value.ok
212
+ ? `已发送 ${value.sent} 条消息${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
213
+ : `发送失败: ${value.error ?? '?'}` },
214
+ ],
215
+ },
216
+ timeoutMs: 60_000,
217
+ async execute(args, exec) {
218
+ const c = await resolveCtx(args, exec);
219
+ const raw = Array.isArray(args?.messages) ? args.messages : [];
220
+ const messages = raw.map((s) => String(s ?? '').trim()).filter((s) => s.length > 0);
221
+ const sent = [];
222
+ if (messages.length > 0) {
223
+ const record = c.routes?.get(c.sessionId);
224
+ const passive = record
225
+ ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
226
+ : undefined;
227
+ for (const msg of messages) {
228
+ try {
229
+ await c.api.sendText(c.target(), msg, passive);
230
+ sent.push(msg);
231
+ }
232
+ catch (error) {
233
+ return {
234
+ ok: false, sent: sent.length,
235
+ error: error instanceof Error ? error.message : String(error),
236
+ };
237
+ }
238
+ }
239
+ // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
240
+ // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
241
+ if (sent.length > 0 && c.target()?.kind === 'c2c') {
242
+ const workspace = c.workspaceOf
243
+ ? await c.workspaceOf()
244
+ : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
245
+ if (workspace && c.sessionId) {
246
+ const file = sessionFileFor({ sessionId: c.sessionId, workspace });
247
+ // 会话文件不存在则无内容可提取(测试/调试 stub 路径跳过,避免挂空定时器)。
248
+ if (existsSync(file)) {
249
+ const charLabel = c.roleId && c.persona ? await charLabelOf(c.persona, c.roleId) : '角色';
250
+ setTimeout(() => {
251
+ void refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log: c.log })
252
+ .catch((error) => c.log?.warn?.('pygmalion: 刷新原始记录失败: %o', error));
253
+ }, 3000);
254
+ }
255
+ }
256
+ }
257
+ }
258
+ // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
259
+ const ra = args?.reawake;
260
+ if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
261
+ return { ok: true, sent: sent.length };
262
+ const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
263
+ if (Number.isFinite(minutes) && minutes > 0) {
264
+ const rw = c.roleId && c.persona?.scheduleRewake
265
+ ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '')
266
+ : { ok: false, atMs: 0, error: '无角色上下文' };
267
+ if (!rw.ok)
268
+ return { ok: false, sent: sent.length, error: `reawake 安排失败: ${rw.error ?? '?'}` };
269
+ return { ok: true, sent: sent.length, reawake: rw.atMs };
270
+ }
271
+ return { ok: true, sent: sent.length };
272
+ },
273
+ },
274
+ // recollect:按需回忆(只在需要回忆/找话题时调用)
275
+ {
276
+ name: 'recollect',
277
+ description: '按需回忆记忆:读取已归档的聊天索引(话题层 topics/ + 日期层 + 特殊记忆 关于TA.md)'
278
+ + '用于引用过去的事、延续话题或找话题。默认返回特殊记忆 + 最近话题索引 + 最近几个日期的索引速查;'
279
+ + '可指定 date=YYYY-MM-DD 读某天,或用 topic 关键字过滤。只在需要回忆时才调用;'
280
+ + '日常不要读写记忆文件(归档由系统自动完成,特殊记忆可直接编辑 关于TA.md)。',
281
+ parameters: {
282
+ type: 'object',
283
+ additionalProperties: false,
284
+ properties: {
285
+ date: { type: 'string', description: '可选,YYYY-MM-DD:只读那一天的索引/原文。' },
286
+ topic: { type: 'string', description: '可选,要回忆的关键字(在特殊记忆/话题/索引/原文里检索)。' },
287
+ limit: { type: 'number', description: '可选,最多读取最近多少个日期的索引(默认 3,上限 10)。' },
288
+ },
289
+ },
290
+ output: {
291
+ schema: {
292
+ type: 'object',
293
+ additionalProperties: false,
294
+ properties: { found: { type: 'boolean' }, text: { type: 'string' } },
295
+ required: ['found', 'text'],
296
+ },
297
+ render: (_args, value) => [
298
+ { type: 'text', text: value.found ? `[回忆]\n${String(value.text).slice(0, 4000)}` : '(记忆中没有相关内容)' },
299
+ ],
300
+ },
301
+ timeoutMs: 20_000,
302
+ async execute(args, exec) {
303
+ const c = await resolveCtx(args, exec);
304
+ const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
305
+ if (!ws) return { found: false, text: '' };
306
+ const mem = join(ws, 'memory');
307
+ const out = [];
308
+ // 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
309
+ try {
310
+ const ta = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
311
+ if (ta && ta !== '(空白,等待你记录对 TA 的了解)')
312
+ out.push(`== 关于TA(特殊记忆)==\n${ta.slice(0, 2000)}`);
313
+ } catch { /* 尚无特殊记忆 */ }
314
+ // 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
315
+ try {
316
+ const subs = (await readdir(join(mem, 'topics'))).filter((n) => !n.startsWith('.')).sort().reverse();
317
+ for (const name of subs.slice(0, 20)) {
318
+ try {
319
+ const ti = await readFile(join(mem, 'topics', name, '索引.md'), 'utf8');
320
+ out.push(`== 话题 ${name} ==\n${ti.slice(0, 1200)}`);
321
+ } catch { /* 该话题无索引 */ }
322
+ }
323
+ } catch { /* 无话题层 */ }
324
+ // 日期层:索引(默认最近 N 天;指定日期则附当日原文片段)
325
+ let dates = [];
326
+ try { dates = (await readdir(mem)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n)).sort().reverse(); } catch { /* no memory yet */ }
327
+ if (dates.length) {
328
+ const limit = Math.min(Math.max(Number(args?.limit) || 3, 1), 10);
329
+ const pick = args?.date ? [String(args.date)] : dates.slice(0, limit);
330
+ for (const d of pick) {
331
+ const idx = join(mem, d, '索引.md');
332
+ const raw = join(mem, d, '原始记录.md');
333
+ try {
334
+ let t = `== ${d} 索引 ==\n` + await readFile(idx, 'utf8');
335
+ if (args?.date && args.date === d) {
336
+ try { t += `\n== ${d} 原文(片段) ==\n` + (await readFile(raw, 'utf8')).slice(0, 2000); } catch { /* 无原文 */ }
337
+ }
338
+ out.push(t);
339
+ } catch { /* 该日无索引 */ }
340
+ }
341
+ }
342
+ let text = out.join('\n\n');
343
+ if (args?.topic) {
344
+ const q = String(args.topic).toLowerCase();
345
+ const filtered = text.split('\n').filter((l) => l.toLowerCase().includes(q));
346
+ text = filtered.length ? filtered.join('\n') : text;
347
+ }
348
+ return text.trim() ? { found: true, text: text.trim().slice(0, 6000) } : { found: false, text: '' };
349
+ },
350
+ },
351
+ // life_run:在插件监管下启动/终止角色生活脚本(dsh 全权决定运行,插件只监管展示)
352
+ {
353
+ name: 'life_run',
354
+ description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
355
+ + '脚本是“角色生活的程序化模拟器”:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
356
+ + '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
357
+ + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“ta 很久没回就去找 ta”。'
358
+ + '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
359
+ + '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
360
+ + '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
361
+ + '要终止用 stop=<runId>。'
362
+ + '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
363
+ + '突发小事件、想 ta 的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
364
+ + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
365
+ + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
366
+ + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
367
+ + '(可以选择沉默)——没有被唤醒的事件就失去了意义。'
368
+ + '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
369
+ + '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
370
+ + '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
371
+ + '注意:wake() 是异步的——一次性脚本务必 await wake(...);长驻循环脚本里调用后要'
372
+ + '保持进程存活,否则请求可能随进程退出(如 process.exit)而丢失。'
373
+ + '注入环境变量:PYG_QQ / PYG_WORKSPACE / PYG_DATA_ROOT / PYG_STATE_FILE / '
374
+ + 'PYG_LAST_USER_AT(最后用户活动时间 epoch ms)/ PYG_TOKEN / PYG_BASE / '
375
+ + 'PYG_HTTP_API_PATH / PYG_OPENID(wake() 的唤醒目标)。',
376
+ parameters: {
377
+ type: 'object',
378
+ additionalProperties: false,
379
+ properties: {
380
+ script: { type: 'string', description: 'life/ 下要启动的脚本文件名(如 script-春天.mjs);省略则启动约定的 main.*/index.*。' },
381
+ reason: { type: 'string', description: '可选:这次启动/终止的缘由(写进运行日志)。' },
382
+ stop: { type: 'string', description: '可选:要终止的运行中脚本 runId(提供时不再启动新脚本)。' },
383
+ },
384
+ },
385
+ output: {
386
+ schema: {
387
+ type: 'object',
388
+ additionalProperties: false,
389
+ properties: {
390
+ ok: { type: 'boolean' },
391
+ runId: { type: 'string' },
392
+ pid: { type: 'number' },
393
+ startedAt: { type: 'number' },
394
+ script: { type: 'string' },
395
+ stopped: { type: 'string' },
396
+ error: { type: 'string' },
397
+ },
398
+ required: ['ok'],
399
+ },
400
+ render: (_args, value) => [{ type: 'text', text: renderLifeRun(value) }],
401
+ },
402
+ timeoutMs: 60_000,
403
+ async execute(args, exec) {
404
+ const c = await resolveCtx(args, exec);
405
+ const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
406
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
407
+
408
+ // stop 模式:终止一个运行中脚本(不启动新脚本)
409
+ if (typeof args?.stop === 'string' && args.stop.trim()) {
410
+ const res = await stopLifeScript(args.stop.trim());
411
+ return res.ok ? { ok: true, stopped: res.runId } : { ok: false, error: res.error || '终止失败' };
412
+ }
413
+
414
+ const scripts = await listLifeScripts(ws);
415
+ const given = typeof args?.script === 'string' ? String(args.script).trim() : '';
416
+ let script;
417
+ if (given) {
418
+ const p = join(ws, 'life', given);
419
+ if (!existsSync(p))
420
+ return { ok: false, error: `life/${given} 不存在(当前脚本:${scripts.join(', ') || '无'})` };
421
+ script = p;
422
+ } else {
423
+ const found = await findLifeScript(ws);
424
+ if (!found)
425
+ return { ok: false, error: scripts.length
426
+ ? `life/ 有脚本但无约定主脚本(${scripts.join(', ')}):请用 script=<文件名> 指定要启动哪个。`
427
+ : 'life/ 下还没有任何脚本——先新建一个(新文件,勿覆盖已有文件)再用 life_run 启动。' };
428
+ script = found;
429
+ }
430
+ try {
431
+ await snapshotLifeScript({ workspace: ws, script, manifest: await readLifeManifest(ws) });
432
+ } catch { /* 快照失败不阻塞启动 */ }
433
+ const lastUserAt = c.routes?.get?.(c.sessionId)?.lastMsgAt;
434
+ const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
435
+ const res = await startLifeScript(script, {
436
+ qq: c.roleId ?? '',
437
+ workspace: ws,
438
+ dataRoot: c.persona?.dataRoot?.(),
439
+ stateFile: c.roleId && c.persona?.roleDir ? join(c.persona.roleDir(c.roleId), 'state.json') : undefined,
440
+ lastUserAt,
441
+ token: c.httpApiToken,
442
+ httpApiPath: c.httpApiPath,
443
+ openid: role?.binding?.openid,
444
+ });
445
+ return res.ok
446
+ ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
447
+ : { ok: false, error: res.error || '启动失败' };
448
+ },
449
+ },
450
+ ];
451
+ }
452
+
453
+ /**
454
+ * 表情包工具定义(meme_save / meme_find / meme_send / meme_update)。
455
+ * 数据层在 src/memebox.js(workspace/memebox/)。与导演工具同机制注册,
456
+ * 经 standing 层按 exec.agent.id 动态解析会话依赖。
457
+ */
458
+ export function buildMemeToolDefs(resolveCtx) {
459
+ const workspaceOfCtx = async (c) => (typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null);
460
+ return [
461
+ // meme_save:存入表情包库(无元数据 → staging 待归类)
462
+ {
463
+ name: 'meme_save',
464
+ description: '把一张表情包图片存入角色表情包库(memebox)。source 可为 https URL、data: URL 或本地绝对路径。'
465
+ + '【重要】只有在你(或视觉子代理)亲眼看图、确认它是值得收藏的好表情包时,才带 content/style/contexts;'
466
+ + '否则(如搜索来的 URL、没亲眼看图)只给 source 不带元数据——系统会自动识别归类并判断是否真表情包。'
467
+ + '带元数据 → 直接归档(ready);不带 → 存待归类区(staging,系统随后自动识别)。',
468
+ parameters: {
469
+ type: 'object',
470
+ additionalProperties: false,
471
+ properties: {
472
+ source: { type: 'string', description: '图片来源:https URL / data: URL / 本地绝对路径。' },
473
+ name: { type: 'string', description: '可选,文件名/昵称。' },
474
+ content: { type: 'string', description: '可选,图片内容描述。' },
475
+ style: { type: 'string', description: '可选,图片风格(如「可爱」「简约」「梗图」)。' },
476
+ contexts: { type: 'array', items: { type: 'string' }, description: '可选,适用语境列表(如「撒娇」「生气」「早安」)。' },
477
+ },
478
+ required: ['source'],
479
+ },
480
+ output: {
481
+ schema: {
482
+ type: 'object', additionalProperties: false,
483
+ properties: { ok: { type: 'boolean' }, memeId: { type: 'string' }, file: { type: 'string' }, status: { type: 'string' }, error: { type: 'string' } },
484
+ required: ['ok'],
485
+ },
486
+ render: (_args, value) => [{ type: 'text', text: value.ok
487
+ ? `已存入表情包库(memeId=${value.memeId}, status=${value.status})`
488
+ : `meme_save 失败: ${value.error ?? '?'}` }],
489
+ },
490
+ timeoutMs: 60_000,
491
+ async execute(args, exec) {
492
+ const c = await resolveCtx(args, exec);
493
+ const ws = await workspaceOfCtx(c);
494
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
495
+ try {
496
+ const r = await saveMeme({ workspace: ws, source: args.source, name: args.name, content: args.content, style: args.style, contexts: args.contexts, log: c.log });
497
+ return noUndefined({ ok: true, memeId: r.memeId, file: r.file, status: r.status });
498
+ }
499
+ catch (error) {
500
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
501
+ }
502
+ },
503
+ },
504
+ // meme_download:把图片 URL / 表情包站点页面批量下载到工作区临时收集目录(供子代理「先下载、再看图、后入库」用)。
505
+ {
506
+ name: 'meme_download',
507
+ description: '把表情包图片下载到临时目录并返回本地路径列表(files)。'
508
+ + '传【图片直链】下载一张;传【表情包站点的列表页/分类页 URL】会抓取页内全部表情包图片批量下载(优先用这种,一次拿一批)。'
509
+ + '收集流程:先用它从友好来源页批量下载 → read_image 逐个看图判定 → 合格后 meme_save(source=某个路径, content/style/contexts) 入库。',
510
+ parameters: {
511
+ type: 'object', additionalProperties: false,
512
+ properties: { url: { type: 'string', description: '图片直链或表情包站点页面 URL。' } },
513
+ required: ['url'],
514
+ },
515
+ output: {
516
+ schema: {
517
+ type: 'object', additionalProperties: false,
518
+ properties: { ok: { type: 'boolean' }, files: { type: 'array', items: { type: 'string' } }, count: { type: 'number' }, error: { type: 'string' } },
519
+ required: ['ok'],
520
+ },
521
+ render: (_args, value) => [{ type: 'text', text: value.ok
522
+ ? `已下载 ${value.count ?? value.files?.length ?? 0} 张图片`
523
+ : `meme_download 失败: ${value.error ?? '?'}` }],
524
+ },
525
+ timeoutMs: 180_000,
526
+ async execute(args, exec) {
527
+ const c = await resolveCtx(args, exec);
528
+ const ws = await workspaceOfCtx(c);
529
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
530
+ try {
531
+ const files = await downloadPageImagesToCollectDir(ws, args.url, c.log);
532
+ return noUndefined({ ok: true, files, count: files.length });
533
+ }
534
+ catch (error) {
535
+ return noUndefined({ ok: false, files: [], count: 0, error: error instanceof Error ? error.message : String(error) });
536
+ }
537
+ },
538
+ },
539
+ // meme_archive:读图判定 + 提取元数据 + 入库,一步原子完成(子代理按文件逐个调用,杜绝 file↔元数据 配对错位)。
540
+ {
541
+ name: 'meme_archive',
542
+ description: '把一张已下载的表情包图片「看图判定 + 提取元数据 + 入库」一步完成。'
543
+ + '传入 meme_download 返回的本地路径,工具会自己读图判断是否合格表情包:'
544
+ + '合格则提取 content/style/contexts 并保存进库,返回 memeId 和归档信息;不合格返回 error。'
545
+ + '收集时对每个下载好的本地路径调用它即可,无需自己 read_image + meme_save。',
546
+ parameters: {
547
+ type: 'object', additionalProperties: false,
548
+ properties: { file: { type: 'string', description: 'meme_download 返回的本地图片绝对路径。' } },
549
+ required: ['file'],
550
+ },
551
+ output: {
552
+ schema: {
553
+ type: 'object', additionalProperties: false,
554
+ properties: { ok: { type: 'boolean' }, memeId: { type: 'string' }, content: { type: 'string' }, style: { type: 'string' }, contexts: { type: 'array', items: { type: 'string' } }, error: { type: 'string' } },
555
+ required: ['ok'],
556
+ },
557
+ render: (_args, value) => [{ type: 'text', text: value.ok
558
+ ? `已归档 memeId=${value.memeId}(${value.content ?? ''}${value.style ? ` / ${value.style}` : ''})`
559
+ : `meme_archive 失败: ${value.error ?? '?'}` }],
560
+ },
561
+ timeoutMs: 120_000,
562
+ async execute(args, exec) {
563
+ const c = await resolveCtx(args, exec);
564
+ const ws = await workspaceOfCtx(c);
565
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
566
+ const parentAgent = exec?.agent;
567
+ if (!parentAgent) return { ok: false, error: '无父 agent 引用' };
568
+ const role = c.roleId ? await c.persona?.loadRole?.(c.roleId) : undefined;
569
+ if (!role) return { ok: false, error: '角色不存在' };
570
+ if (!c.subagents) return { ok: false, error: 'subagents 服务不可用' };
571
+ const vision = await resolveVisionConfig(role, { llm: c.llm, log: c.log });
572
+ try {
573
+ const r = await archiveImageBySubagent({ subagents: c.subagents, parentAgent, log: c.log }, { file: args.file, vision });
574
+ if (r?.ok !== true || r.valid !== true) {
575
+ return noUndefined({ ok: false, error: r?.error ?? '非表情包' });
576
+ }
577
+ const s = await saveMeme({ workspace: ws, source: args.file, content: r.content, style: r.style, contexts: r.contexts, log: c.log });
578
+ return noUndefined({ ok: true, memeId: s.memeId, content: r.content, style: r.style, contexts: r.contexts });
579
+ }
580
+ catch (error) {
581
+ return noUndefined({ ok: false, error: error instanceof Error ? error.message : String(error) });
582
+ }
583
+ },
584
+ },
585
+ // meme_find:按内容/风格/语境检索表情包库
586
+ {
587
+ name: 'meme_find',
588
+ description: '在角色表情包库(memebox)里按关键词检索表情包:可搜内容、风格、适用语境(任意命中即返回)。'
589
+ + '返回命中列表(含 memeId、内容、风格、语境、是否已归类)。聊天想发合适表情包时先用它找。',
590
+ parameters: {
591
+ type: 'object', additionalProperties: false,
592
+ properties: {
593
+ query: { type: 'string', description: '可选,任意关键词(在内容/风格/语境里匹配)。' },
594
+ style: { type: 'string', description: '可选,只按风格过滤。' },
595
+ context: { type: 'string', description: '可选,只按适用语境过滤。' },
596
+ },
597
+ },
598
+ output: {
599
+ schema: {
600
+ type: 'object', additionalProperties: false,
601
+ properties: {
602
+ found: { type: 'boolean' },
603
+ items: { type: 'array', items: { type: 'object' } },
604
+ error: { type: 'string' },
605
+ },
606
+ required: ['found'],
607
+ },
608
+ render: (_args, value) => {
609
+ if (!value.found) return [{ type: 'text', text: '(表情包库没有匹配项)' }];
610
+ const lines = value.items.map((m) => `- ${m.memeId} ${m.status === 'ready' ? '' : '[待归类]'} ${m.content || ''}${m.style ? `(${m.style})` : ''}${m.contexts?.length ? ` 适用: ${m.contexts.join('、')}` : ''}`);
611
+ return [{ type: 'text', text: `找到 ${value.items.length} 个表情包:\n${lines.join('\n')}` }];
612
+ },
613
+ },
614
+ timeoutMs: 15_000,
615
+ async execute(args, exec) {
616
+ const c = await resolveCtx(args, exec);
617
+ const ws = await workspaceOfCtx(c);
618
+ if (!ws) return { found: false, items: [], error: '无角色工作区上下文' };
619
+ const hits = await findMemes(ws, { query: args.query, style: args.style, context: args.context });
620
+ return noUndefined({
621
+ found: hits.length > 0,
622
+ items: hits.map((e) => ({
623
+ memeId: e.id, content: e.content, style: e.style,
624
+ contexts: e.contexts ?? [], status: e.status, name: e.name ?? '',
625
+ })),
626
+ });
627
+ },
628
+ },
629
+ // meme_send:发送一张表情包
630
+ {
631
+ name: 'meme_send',
632
+ description: '向当前 QQ 聊天发送一张表情包图片。用 memeId(优先,从 meme_find 拿到)或本地文件路径。'
633
+ + '可带 text 作为配文。发送成功会记录使用时间。',
634
+ parameters: {
635
+ type: 'object', additionalProperties: false,
636
+ properties: {
637
+ memeId: { type: 'string', description: '可选,表情包 id(meme_find 返回)。' },
638
+ file: { type: 'string', description: '可选,本地图片文件绝对路径(memeId 与 file 至少给一个)。' },
639
+ text: { type: 'string', description: '可选,随图发送的配文。' },
640
+ },
641
+ },
642
+ output: {
643
+ schema: {
644
+ type: 'object', additionalProperties: false,
645
+ properties: { sent: { type: 'boolean' }, memeId: { type: 'string' }, file: { type: 'string' }, error: { type: 'string' } },
646
+ required: ['sent'],
647
+ },
648
+ render: (_args, value) => [{ type: 'text', text: value.sent
649
+ ? `已发送表情包${value.memeId ? `(${value.memeId})` : ''}`
650
+ : `meme_send 失败: ${value.error ?? '?'}` }],
651
+ },
652
+ timeoutMs: 120_000,
653
+ async execute(args, exec) {
654
+ const c = await resolveCtx(args, exec);
655
+ const ws = await workspaceOfCtx(c);
656
+ let path;
657
+ if (typeof args?.memeId === 'string' && args.memeId.trim()) {
658
+ if (!ws) return { sent: false, error: '无角色工作区上下文' };
659
+ path = await memeFileFor(ws, args.memeId.trim());
660
+ if (!path) return { sent: false, memeId: args.memeId, error: `表情包不存在: ${args.memeId}` };
661
+ }
662
+ else if (typeof args?.file === 'string' && args.file.trim()) {
663
+ path = args.file.trim();
664
+ }
665
+ else {
666
+ return { sent: false, error: '需要 memeId 或 file' };
667
+ }
668
+ try {
669
+ await c.api.sendMedia(c.target(), 'image', path, { text: args?.text });
670
+ if (typeof args?.memeId === 'string' && args.memeId.trim() && ws) {
671
+ await recordMemeUsed(ws, args.memeId.trim()).catch(() => {});
672
+ }
673
+ return noUndefined({ sent: true, memeId: args?.memeId, file: path });
674
+ }
675
+ catch (error) {
676
+ return noUndefined({ sent: false, memeId: args?.memeId, error: error instanceof Error ? error.message : String(error) });
677
+ }
678
+ },
679
+ },
680
+ // meme_update:编辑元数据(staging 补元数据后自动归类)
681
+ {
682
+ name: 'meme_update',
683
+ description: '编辑表情包元数据:content(内容)/style(风格)/contexts(适用语境)/name。'
684
+ + '对待归类(staging)的表情包补上元数据后会自动归入已归档区。',
685
+ parameters: {
686
+ type: 'object', additionalProperties: false,
687
+ properties: {
688
+ memeId: { type: 'string', description: '表情包 id。' },
689
+ content: { type: 'string', description: '可选,内容描述。' },
690
+ style: { type: 'string', description: '可选,风格。' },
691
+ contexts: { type: 'array', items: { type: 'string' }, description: '可选,适用语境列表。' },
692
+ name: { type: 'string', description: '可选,名字。' },
693
+ },
694
+ required: ['memeId'],
695
+ },
696
+ output: {
697
+ schema: {
698
+ type: 'object', additionalProperties: false,
699
+ properties: { ok: { type: 'boolean' }, error: { type: 'string' } },
700
+ required: ['ok'],
701
+ },
702
+ render: (_args, value) => [{ type: 'text', text: value.ok ? '表情包元数据已更新' : `meme_update 失败: ${value.error ?? '?'}` }],
703
+ },
704
+ timeoutMs: 15_000,
705
+ async execute(args, exec) {
706
+ const c = await resolveCtx(args, exec);
707
+ const ws = await workspaceOfCtx(c);
708
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
709
+ const r = await updateMeme(ws, args.memeId, {
710
+ content: args.content, style: args.style, contexts: args.contexts, name: args.name,
711
+ });
712
+ return noUndefined(r.ok ? { ok: true } : { ok: false, error: r.error });
713
+ },
714
+ },
715
+ // subagent_meme:委托表情包子代理按方向收集并自动归档(主 agent 只给方向,不参与收集)。
716
+ // 子代理自主「web_search → meme_download 下载 → read_image 看图判定 → meme_save 入库」,
717
+ // 入库即 ready,主 agent 直接 meme_send 可用;与 heartbeat 定期收集共用 withMemeLock 互斥。
718
+ {
719
+ name: 'subagent_meme',
720
+ description: '让表情包子代理按指定方向收集表情包并自动归档。传入收集方向(如「猫猫撒娇表情包」),'
721
+ + '并用 count 指定要收集的张数;子代理会自主搜索、自己看图判定、把合格的表情包存进角色表情包库并写好索引;'
722
+ + '完成后返回 memeId 列表,直接用 meme_send(memeId) 发送即可。你只负责给方向和张数,不参与收集。',
723
+ parameters: {
724
+ type: 'object', additionalProperties: false,
725
+ properties: {
726
+ goal: { type: 'string', description: '收集方向,如「猫猫撒娇表情包」「简约风格生活梗图」。' },
727
+ count: { type: 'integer', description: '要收集的表情包张数(由你指定,如 8);不传则尽量多收集。' },
728
+ },
729
+ required: ['goal'],
730
+ },
731
+ output: {
732
+ schema: {
733
+ type: 'object', additionalProperties: false,
734
+ properties: {
735
+ ok: { type: 'boolean' },
736
+ collected: { type: 'number' },
737
+ classified: { type: 'number' },
738
+ removed: { type: 'number' },
739
+ memeIds: { type: 'array', items: { type: 'string' } },
740
+ error: { type: 'string' },
741
+ },
742
+ required: ['ok'],
743
+ },
744
+ render: (_args, value) => {
745
+ if (!value.ok) return [{ type: 'text', text: `subagent_meme 失败: ${value.error ?? '?'}` }];
746
+ if (value.memeIds?.length) return [{ type: 'text', text: `已收集 ${value.collected ?? 0} 张,归档 ${value.classified ?? 0} 张(剔除 ${value.removed ?? 0} 张非表情包)。可用 memeId 直接发送:${value.memeIds.join('、')}` }];
747
+ return [{ type: 'text', text: `收集完成,但没有找到符合方向的表情包(收集 ${value.collected ?? 0},有效 ${value.classified ?? 0})。` }];
748
+ },
749
+ },
750
+ timeoutMs: 600_000,
751
+ async execute(args, exec) {
752
+ const c = await resolveCtx(args, exec);
753
+ const ws = await workspaceOfCtx(c);
754
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
755
+ if (!c.subagents) return { ok: false, error: 'subagents 服务不可用(表情包子代理无法启动)' };
756
+ const parentAgent = exec?.agent;
757
+ if (!parentAgent) return { ok: false, error: '无父 agent 引用' };
758
+ const role = c.roleId ? await c.persona?.loadRole?.(c.roleId) : undefined;
759
+ if (!role) return { ok: false, error: '角色不存在' };
760
+ const vision = await resolveVisionConfig(role, { llm: c.llm, log: c.log });
761
+ memeTrace('subagent_meme', `role=${c.roleId} goal=${args.goal ?? '(none)'} count=${args.count ?? '(默认)'} vision=${vision.provider}/${vision.model} workspace=${ws}`);
762
+ const r = await withMemeLock(c.roleId, () => collectAndClassify(
763
+ { subagents: c.subagents, parentAgent, workspace: ws, vision, log: c.log },
764
+ { goal: args.goal, count: args.count },
765
+ ));
766
+ memeTrace('subagent_meme', `done: ok=${r.ok} collected=${r.collected} classified=${r.classified} removed=${r.removed} memeIds=${(r.memeIds ?? []).length} error=${r.error ?? '(none)'}`);
767
+ return noUndefined({ ok: r.ok, collected: r.collected, classified: r.classified, removed: r.removed, memeIds: r.memeIds, error: r.error });
768
+ },
769
+ },
770
+ // meme_read:主 agent 无视觉时经视觉子代理读图(收到图片但看不到内容时用)。
771
+ {
772
+ name: 'meme_read',
773
+ description: '看一张图:当你看不到图片内容时(模型没有读图能力),传用户刚发图片的本地路径'
774
+ + '(工作区 .qq-media/inbound/ 下最新那张)或 memeId,让视觉子代理读图,把内容/风格/适用语境描述给你。',
775
+ parameters: {
776
+ type: 'object', additionalProperties: false,
777
+ properties: {
778
+ memeId: { type: 'string', description: '可选,表情包 id(meme_find 返回;传它则读取对应图片文件)。' },
779
+ file: { type: 'string', description: '可选,本地图片绝对路径(memeId 与 file 至少给一个)。' },
780
+ },
781
+ },
782
+ output: {
783
+ schema: {
784
+ type: 'object', additionalProperties: false,
785
+ properties: {
786
+ ok: { type: 'boolean' },
787
+ content: { type: 'string' },
788
+ style: { type: 'string' },
789
+ contexts: { type: 'array', items: { type: 'string' } },
790
+ error: { type: 'string' },
791
+ },
792
+ required: ['ok'],
793
+ },
794
+ render: (_args, value) => {
795
+ if (!value.ok) return [{ type: 'text', text: `meme_read 失败: ${value.error ?? '?'}` }];
796
+ const lines = [`图片内容:${value.content || '(无描述)'}`];
797
+ if (value.style) lines.push(`风格:${value.style}`);
798
+ if (value.contexts?.length) lines.push(`适用语境:${value.contexts.join('、')}`);
799
+ return [{ type: 'text', text: lines.join('\n') }];
800
+ },
801
+ },
802
+ timeoutMs: 240_000,
803
+ async execute(args, exec) {
804
+ const c = await resolveCtx(args, exec);
805
+ const ws = await workspaceOfCtx(c);
806
+ let file;
807
+ if (typeof args?.memeId === 'string' && args.memeId.trim()) {
808
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
809
+ file = await memeFileFor(ws, args.memeId.trim());
810
+ if (!file) return { ok: false, error: `表情包不存在: ${args.memeId}` };
811
+ }
812
+ else if (typeof args?.file === 'string' && args.file.trim()) {
813
+ file = args.file.trim();
814
+ }
815
+ else {
816
+ return { ok: false, error: '需要 memeId 或 file' };
817
+ }
818
+ if (!c.subagents) return { ok: false, error: 'subagents 服务不可用(视觉子代理无法启动)' };
819
+ const parentAgent = exec?.agent;
820
+ if (!parentAgent) return { ok: false, error: '无父 agent 引用' };
821
+ const role = c.roleId ? await c.persona?.loadRole?.(c.roleId) : undefined;
822
+ const vision = role ? await resolveVisionConfig(role, { llm: c.llm, log: c.log }) : undefined;
823
+ if (!vision) return { ok: false, error: '无法解析视觉模型' };
824
+ return noUndefined(await readImageBySubagent({ subagents: c.subagents, parentAgent, log: c.log }, { file, vision }));
825
+ },
826
+ },
827
+ ];
828
+ }
829
+
830
+ /** own 层注册 QQ 工具(setup 兜底路径,签名与旧版一致)。 */
831
+ export function registerQQTools(agentCtx, sessionId, api, routeTarget) {
832
+ const tools = agentCtx.tools;
833
+ if (tools === undefined)
834
+ return;
835
+ const target = () => routeTarget() ?? targetOfSession(sessionId);
836
+ const resolveCtx = async (_args, exec) => ({
837
+ sessionId: exec?.agent?.id ?? sessionId,
838
+ api, routes: undefined, target,
839
+ roleId: undefined, httpApiToken: undefined, httpApiPath: undefined, persona: undefined, log: undefined, workspaceOf: undefined,
840
+ });
841
+ for (const def of buildQQToolDefs(resolveCtx))
842
+ tools.register(def);
843
+ }
844
+
845
+ /**
846
+ * Pygmalion 导演发送工具:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
847
+ * 注册进会话 own 层(setup 兜底路径,签名与旧版一致)。
848
+ */
849
+ export function registerDirectorTools(agentCtx, sessionId, deps) {
850
+ const tools = agentCtx.tools;
851
+ if (tools === undefined)
852
+ return false;
853
+ const target = () => deps.target?.() ?? targetOfSession(sessionId);
854
+ const resolveCtx = async (_args, exec) => ({
855
+ sessionId: exec?.agent?.id ?? sessionId,
856
+ api: deps.api, routes: deps.routes, target,
857
+ roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
858
+ persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
859
+ subagents: deps.subagents, llm: deps.llm,
860
+ });
861
+ for (const def of buildDirectorToolDefs(resolveCtx))
862
+ tools.register(def);
863
+ for (const def of buildMemeToolDefs(resolveCtx))
864
+ tools.register(def);
865
+ return true;
866
+ }
867
+
868
+ /**
869
+ * 把 pygmalion 全套工具注册进 standing 层(由 preset 桥插件经宿主服务调用)。
870
+ * 工具定义每进程一份;执行时按 exec.agent.id 从 depsFor(sessionId) 动态解析每会话依赖,
871
+ * 因此 resume 恢复会话后 dispatch 依然可达(与 preset 内 fs/bash 工具同一层)。
872
+ * @param ctx 桥插件上下文(standing 层 scope 上下文)
873
+ * @param depsFor 会话依赖解析函数:sessionId → { api, routes, target, roleId, httpApiToken, persona, log, workspaceOf }
874
+ * (可能为 async:宿主服务可在未命中时按 sessionId 惰性构造依赖)
875
+ * @returns 是否完成注册
876
+ */
877
+ export function registerStandingTools(ctx, depsFor) {
878
+ const tools = ctx.tools;
879
+ if (tools === undefined)
880
+ return false;
881
+ const resolveCtx = async (_args, exec) => {
882
+ const sessionId = exec?.agent?.id;
883
+ if (!sessionId)
884
+ throw new Error('pygmalion: 工具调用缺少会话上下文(exec.agent.id 为空)');
885
+ const deps = await depsFor(sessionId);
886
+ if (deps === undefined)
887
+ throw new Error(`pygmalion: 会话 ${sessionId} 的 pygmalion 上下文未注册(setup 未运行?该 agent 并非由 pygmalion 启动?)`);
888
+ return {
889
+ sessionId,
890
+ api: deps.api, routes: deps.routes,
891
+ target: () => deps.target?.() ?? targetOfSession(sessionId),
892
+ roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
893
+ persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
894
+ subagents: deps.subagents, llm: deps.llm,
895
+ };
896
+ };
897
+ for (const def of buildQQToolDefs(resolveCtx))
898
+ tools.register(def);
899
+ for (const def of buildDirectorToolDefs(resolveCtx))
900
+ tools.register(def);
901
+ for (const def of buildMemeToolDefs(resolveCtx))
902
+ tools.register(def);
903
+ return true;
904
+ }