pygmalion 0.1.4 → 0.1.6

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,502 +1,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
-
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(正数=多少分钟后若用户没回则系统再唤醒你;"none"或省略=不安排),'
161
- + 'messages 为空数组时可只安排 reawake 而本次不发。'
162
- + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
163
- + '如果你决定此刻不打扰对方,就不要调用本工具。',
164
- parameters: {
165
- type: 'object',
166
- additionalProperties: false,
167
- properties: {
168
- messages: {
169
- type: 'array',
170
- items: { type: 'string' },
171
- description: '要逐条发送的聊天消息列表;空数组或省略 = 不发送(沉默)。',
172
- },
173
- reawake: {
174
- oneOf: [{ type: 'number' }, { type: 'string' }],
175
- description: '可选:安排多少分钟后延时唤醒你(建议 5~30)。写正数会登记等待队列,'
176
- + '届时用户若没回则系统唤醒你继续;写 "none" 或省略则不安排。',
177
- },
178
- reason: {
179
- type: 'string',
180
- description: '可选:reawake 到期时唤醒你的缘由(你想继续说的话/想确认的事)。',
181
- },
182
- },
183
- },
184
- output: {
185
- schema: {
186
- type: 'object',
187
- additionalProperties: false,
188
- properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
189
- required: ['ok', 'sent'],
190
- },
191
- render: (_args, value) => [
192
- { type: 'text', text: value.ok
193
- ? `已发送 ${value.sent} 条消息${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
194
- : `发送失败: ${value.error ?? '?'}` },
195
- ],
196
- },
197
- timeoutMs: 60_000,
198
- async execute(args, exec) {
199
- const c = await resolveCtx(args, exec);
200
- const raw = Array.isArray(args?.messages) ? args.messages : [];
201
- const messages = raw.map((s) => String(s ?? '').trim()).filter((s) => s.length > 0);
202
- const sent = [];
203
- if (messages.length > 0) {
204
- const record = c.routes?.get(c.sessionId);
205
- const passive = record
206
- ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
207
- : undefined;
208
- for (const msg of messages) {
209
- try {
210
- await c.api.sendText(c.target(), msg, passive);
211
- sent.push(msg);
212
- }
213
- catch (error) {
214
- return {
215
- ok: false, sent: sent.length,
216
- error: error instanceof Error ? error.message : String(error),
217
- };
218
- }
219
- }
220
- // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
221
- // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
222
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
223
- const workspace = c.workspaceOf
224
- ? await c.workspaceOf()
225
- : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
226
- if (workspace && c.sessionId) {
227
- const file = sessionFileFor({ sessionId: c.sessionId, workspace });
228
- // 会话文件不存在则无内容可提取(测试/调试 stub 路径跳过,避免挂空定时器)。
229
- if (existsSync(file)) {
230
- const charLabel = c.roleId && c.persona ? await charLabelOf(c.persona, c.roleId) : '角色';
231
- setTimeout(() => {
232
- void refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log: c.log })
233
- .catch((error) => c.log?.warn?.('pygmalion: 刷新原始记录失败: %o', error));
234
- }, 3000);
235
- }
236
- }
237
- }
238
- }
239
- // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
240
- const ra = args?.reawake;
241
- if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
242
- return { ok: true, sent: sent.length };
243
- const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
244
- if (Number.isFinite(minutes) && minutes > 0) {
245
- const rw = c.roleId && c.persona?.scheduleRewake
246
- ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '')
247
- : { ok: false, atMs: 0, error: '无角色上下文' };
248
- if (!rw.ok)
249
- return { ok: false, sent: sent.length, error: `reawake 安排失败: ${rw.error ?? '?'}` };
250
- return { ok: true, sent: sent.length, reawake: rw.atMs };
251
- }
252
- return { ok: true, sent: sent.length };
253
- },
254
- },
255
- // recollect:按需回忆(只在需要回忆/找话题时调用)
256
- {
257
- name: 'recollect',
258
- description: '按需回忆记忆:读取已归档的聊天索引(话题层 topics/ + 日期层 + 特殊记忆 关于TA.md)'
259
- + '用于引用过去的事、延续话题或找话题。默认返回特殊记忆 + 最近话题索引 + 最近几个日期的索引速查;'
260
- + '可指定 date=YYYY-MM-DD 读某天,或用 topic 关键字过滤。只在需要回忆时才调用;'
261
- + '日常不要读写记忆文件(归档由系统自动完成,特殊记忆可直接编辑 关于TA.md)。',
262
- parameters: {
263
- type: 'object',
264
- additionalProperties: false,
265
- properties: {
266
- date: { type: 'string', description: '可选,YYYY-MM-DD:只读那一天的索引/原文。' },
267
- topic: { type: 'string', description: '可选,要回忆的关键字(在特殊记忆/话题/索引/原文里检索)。' },
268
- limit: { type: 'number', description: '可选,最多读取最近多少个日期的索引(默认 3,上限 10)。' },
269
- },
270
- },
271
- output: {
272
- schema: {
273
- type: 'object',
274
- additionalProperties: false,
275
- properties: { found: { type: 'boolean' }, text: { type: 'string' } },
276
- required: ['found', 'text'],
277
- },
278
- render: (_args, value) => [
279
- { type: 'text', text: value.found ? `[回忆]\n${String(value.text).slice(0, 4000)}` : '(记忆中没有相关内容)' },
280
- ],
281
- },
282
- timeoutMs: 20_000,
283
- async execute(args, exec) {
284
- const c = await resolveCtx(args, exec);
285
- const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
286
- if (!ws) return { found: false, text: '' };
287
- const mem = join(ws, 'memory');
288
- const out = [];
289
- // 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
290
- try {
291
- const ta = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
292
- if (ta && ta !== '(空白,等待你记录对 TA 的了解)')
293
- out.push(`== 关于TA(特殊记忆)==\n${ta.slice(0, 2000)}`);
294
- } catch { /* 尚无特殊记忆 */ }
295
- // 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
296
- try {
297
- const subs = (await readdir(join(mem, 'topics'))).filter((n) => !n.startsWith('.')).sort().reverse();
298
- for (const name of subs.slice(0, 20)) {
299
- try {
300
- const ti = await readFile(join(mem, 'topics', name, '索引.md'), 'utf8');
301
- out.push(`== 话题 ${name} ==\n${ti.slice(0, 1200)}`);
302
- } catch { /* 该话题无索引 */ }
303
- }
304
- } catch { /* 无话题层 */ }
305
- // 日期层:索引(默认最近 N 天;指定日期则附当日原文片段)
306
- let dates = [];
307
- try { dates = (await readdir(mem)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n)).sort().reverse(); } catch { /* no memory yet */ }
308
- if (dates.length) {
309
- const limit = Math.min(Math.max(Number(args?.limit) || 3, 1), 10);
310
- const pick = args?.date ? [String(args.date)] : dates.slice(0, limit);
311
- for (const d of pick) {
312
- const idx = join(mem, d, '索引.md');
313
- const raw = join(mem, d, '原始记录.md');
314
- try {
315
- let t = `== ${d} 索引 ==\n` + await readFile(idx, 'utf8');
316
- if (args?.date && args.date === d) {
317
- try { t += `\n== ${d} 原文(片段) ==\n` + (await readFile(raw, 'utf8')).slice(0, 2000); } catch { /* 无原文 */ }
318
- }
319
- out.push(t);
320
- } catch { /* 该日无索引 */ }
321
- }
322
- }
323
- let text = out.join('\n\n');
324
- if (args?.topic) {
325
- const q = String(args.topic).toLowerCase();
326
- const filtered = text.split('\n').filter((l) => l.toLowerCase().includes(q));
327
- text = filtered.length ? filtered.join('\n') : text;
328
- }
329
- return text.trim() ? { found: true, text: text.trim().slice(0, 6000) } : { found: false, text: '' };
330
- },
331
- },
332
- // life_run:在插件监管下启动/终止角色生活脚本(dsh 全权决定运行,插件只监管展示)
333
- {
334
- name: 'life_run',
335
- description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
336
- + '脚本是「角色生活的程序化模拟器」:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
337
- + '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
338
- + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的「ta 很久没回就去找 ta」。'
339
- + '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
340
- + '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
341
- + '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
342
- + '要终止用 stop=<runId>。'
343
- + '脚本以「有事件就唤醒」为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
344
- + '突发小事件、想 ta 的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
345
- + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
346
- + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
347
- + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、怎么开口由你(导演)被唤醒后自行判断'
348
- + '(可沉默)——不唤醒,脚本里设计的事件就白做了。'
349
- + '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
350
- + '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
351
- + '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
352
- + '注意:wake() 是异步的——一次性脚本务必 await wake(...);长驻循环脚本里调用后要'
353
- + '保持进程存活,否则请求可能随进程退出(如 process.exit)而丢失。'
354
- + '注入环境变量:PYG_QQ / PYG_WORKSPACE / PYG_DATA_ROOT / PYG_STATE_FILE / '
355
- + 'PYG_LAST_USER_AT(最后用户活动时间 epoch ms)/ PYG_TOKEN / PYG_BASE / '
356
- + 'PYG_HTTP_API_PATH / PYG_OPENID(wake() 的唤醒目标)。',
357
- parameters: {
358
- type: 'object',
359
- additionalProperties: false,
360
- properties: {
361
- script: { type: 'string', description: 'life/ 下要启动的脚本文件名(如 script-春天.mjs);省略则启动约定的 main.*/index.*。' },
362
- reason: { type: 'string', description: '可选:这次启动/终止的缘由(写进运行日志)。' },
363
- stop: { type: 'string', description: '可选:要终止的运行中脚本 runId(提供时不再启动新脚本)。' },
364
- },
365
- },
366
- output: {
367
- schema: {
368
- type: 'object',
369
- additionalProperties: false,
370
- properties: {
371
- ok: { type: 'boolean' },
372
- runId: { type: 'string' },
373
- pid: { type: 'number' },
374
- startedAt: { type: 'number' },
375
- script: { type: 'string' },
376
- stopped: { type: 'string' },
377
- error: { type: 'string' },
378
- },
379
- required: ['ok'],
380
- },
381
- render: (_args, value) => [{ type: 'text', text: renderLifeRun(value) }],
382
- },
383
- timeoutMs: 60_000,
384
- async execute(args, exec) {
385
- const c = await resolveCtx(args, exec);
386
- const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
387
- if (!ws) return { ok: false, error: '无角色工作区上下文' };
388
-
389
- // stop 模式:终止一个运行中脚本(不启动新脚本)
390
- if (typeof args?.stop === 'string' && args.stop.trim()) {
391
- const res = await stopLifeScript(args.stop.trim());
392
- return res.ok ? { ok: true, stopped: res.runId } : { ok: false, error: res.error || '终止失败' };
393
- }
394
-
395
- const scripts = await listLifeScripts(ws);
396
- const given = typeof args?.script === 'string' ? String(args.script).trim() : '';
397
- let script;
398
- if (given) {
399
- const p = join(ws, 'life', given);
400
- if (!existsSync(p))
401
- return { ok: false, error: `life/${given} 不存在(当前脚本:${scripts.join(', ') || '无'})` };
402
- script = p;
403
- } else {
404
- const found = await findLifeScript(ws);
405
- if (!found)
406
- return { ok: false, error: scripts.length
407
- ? `life/ 有脚本但无约定主脚本(${scripts.join(', ')}):请用 script=<文件名> 指定要启动哪个。`
408
- : 'life/ 下还没有任何脚本——先新建一个(新文件,勿覆盖已有文件)再用 life_run 启动。' };
409
- script = found;
410
- }
411
- try {
412
- await snapshotLifeScript({ workspace: ws, script, manifest: await readLifeManifest(ws) });
413
- } catch { /* 快照失败不阻塞启动 */ }
414
- const lastUserAt = c.routes?.get?.(c.sessionId)?.lastMsgAt;
415
- const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
416
- const res = await startLifeScript(script, {
417
- qq: c.roleId ?? '',
418
- workspace: ws,
419
- dataRoot: c.persona?.dataRoot?.(),
420
- stateFile: c.roleId && c.persona?.roleDir ? join(c.persona.roleDir(c.roleId), 'state.json') : undefined,
421
- lastUserAt,
422
- token: c.httpApiToken,
423
- httpApiPath: c.httpApiPath,
424
- openid: role?.binding?.openid,
425
- });
426
- return res.ok
427
- ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
428
- : { ok: false, error: res.error || '启动失败' };
429
- },
430
- },
431
- ];
432
- }
433
-
434
- /** own 层注册 QQ 工具(setup 兜底路径,签名与旧版一致)。 */
435
- export function registerQQTools(agentCtx, sessionId, api, routeTarget) {
436
- const tools = agentCtx.tools;
437
- if (tools === undefined)
438
- return;
439
- const target = () => routeTarget() ?? targetOfSession(sessionId);
440
- const resolveCtx = async (_args, exec) => ({
441
- sessionId: exec?.agent?.id ?? sessionId,
442
- api, routes: undefined, target,
443
- roleId: undefined, httpApiToken: undefined, httpApiPath: undefined, persona: undefined, log: undefined, workspaceOf: undefined,
444
- });
445
- for (const def of buildQQToolDefs(resolveCtx))
446
- tools.register(def);
447
- }
448
-
449
- /**
450
- * Pygmalion 导演发送工具:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
451
- * 注册进会话 own 层(setup 兜底路径,签名与旧版一致)。
452
- */
453
- export function registerDirectorTools(agentCtx, sessionId, deps) {
454
- const tools = agentCtx.tools;
455
- if (tools === undefined)
456
- return false;
457
- const target = () => deps.target?.() ?? targetOfSession(sessionId);
458
- const resolveCtx = async (_args, exec) => ({
459
- sessionId: exec?.agent?.id ?? sessionId,
460
- api: deps.api, routes: deps.routes, target,
461
- roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
462
- persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
463
- });
464
- for (const def of buildDirectorToolDefs(resolveCtx))
465
- tools.register(def);
466
- return true;
467
- }
468
-
469
- /**
470
- * 把 pygmalion 全套工具注册进 standing 层(由 preset 桥插件经宿主服务调用)。
471
- * 工具定义每进程一份;执行时按 exec.agent.id 从 depsFor(sessionId) 动态解析每会话依赖,
472
- * 因此 resume 恢复会话后 dispatch 依然可达(与 preset 内 fs/bash 工具同一层)。
473
- * @param ctx 桥插件上下文(standing 层 scope 上下文)
474
- * @param depsFor 会话依赖解析函数:sessionId → { api, routes, target, roleId, httpApiToken, persona, log, workspaceOf }
475
- * (可能为 async:宿主服务可在未命中时按 sessionId 惰性构造依赖)
476
- * @returns 是否完成注册
477
- */
478
- export function registerStandingTools(ctx, depsFor) {
479
- const tools = ctx.tools;
480
- if (tools === undefined)
481
- return false;
482
- const resolveCtx = async (_args, exec) => {
483
- const sessionId = exec?.agent?.id;
484
- if (!sessionId)
485
- throw new Error('pygmalion: 工具调用缺少会话上下文(exec.agent.id 为空)');
486
- const deps = await depsFor(sessionId);
487
- if (deps === undefined)
488
- throw new Error(`pygmalion: 会话 ${sessionId} 的 pygmalion 上下文未注册(setup 未运行?该 agent 并非由 pygmalion 启动?)`);
489
- return {
490
- sessionId,
491
- api: deps.api, routes: deps.routes,
492
- target: () => deps.target?.() ?? targetOfSession(sessionId),
493
- roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
494
- persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
495
- };
496
- };
497
- for (const def of buildQQToolDefs(resolveCtx))
498
- tools.register(def);
499
- for (const def of buildDirectorToolDefs(resolveCtx))
500
- tools.register(def);
501
- return true;
502
- }
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
+ }