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/package.json +1 -1
- package/preset/pygmalion-director/agent.cordis.yml +204 -161
- package/src/active-session.js +25 -2
- package/src/agent-life.js +94 -17
- package/src/bot-factory.js +285 -282
- package/src/heartbeat.js +411 -352
- package/src/inbound.js +790 -770
- package/src/index.js +230 -210
- package/src/llm-provider.js +71 -27
- package/src/meme-worker.js +397 -0
- package/src/memebox.js +348 -0
- package/src/persona.js +397 -380
- package/src/setup-agent.js +3 -1
- package/src/tools.js +904 -511
- package/src/wakeup.js +202 -208
- package/src/web-public/app.js +488 -381
- package/src/web-public/index.html +157 -130
- package/src/web-public/style.css +51 -44
- package/src/web-server.js +581 -506
- package/templates/sample-life.mjs +6 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 表情包自动维护工作器(插件驱动):收集/识别由视觉 subagent 完成,落库由插件完成。
|
|
3
|
+
*
|
|
4
|
+
* 分工(导演完全脱离表情包任务):
|
|
5
|
+
* - 收集:subagent 自主「web_search 找候选 → meme_download 下载 → read_image 看图判定 → meme_save 入库」,
|
|
6
|
+
* 入库即 ready(带元数据),主 agent 直接 meme_find/meme_send 可用,无需再归档。
|
|
7
|
+
* - 识别:inbound 用户发来的图落 staging 后,subagent 用 read_image 读取,返回 content/style/contexts,
|
|
8
|
+
* 插件用 updateMeme 写回元数据(自动归类)。
|
|
9
|
+
* - 保存/存储:由 memebox.js 完成;导演只负责 meme_find/meme_send 使用。
|
|
10
|
+
*
|
|
11
|
+
* subagent 经 ctx.subagents.start('spawn') 启动,以角色的导演 agent 为父(谱系锚,
|
|
12
|
+
* 导演不参与处理);视觉 provider/model 按角色解析(resolveVisionConfig)——
|
|
13
|
+
* 自定义 provider(apiUrl/apiKey)的角色走其自身 route,未显式配视觉模型时回退内置 deepseek。
|
|
14
|
+
*/
|
|
15
|
+
import { listMemes, updateMeme, deleteMeme, memeFileFor } from './memebox.js';
|
|
16
|
+
import { providerRoute, roleUsesCustomProvider, roleUsesCustomSubagentApi, memeVisionRoute } from './llm-provider.js';
|
|
17
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
18
|
+
import { rm } from 'node:fs/promises';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
|
|
21
|
+
/** 视觉兜底模型(内置 deepseek 视觉;未显式配 subagent 视觉 API 时回退)。 */
|
|
22
|
+
export const DEFAULT_VISION = { provider: 'deepseek-official', model: 'deepseek-v4-flash-vision-exp' };
|
|
23
|
+
const WORKER_SIGNAL_TIMEOUT_MS = 480_000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 始终可用的 meme-worker 追踪日志(不受 config.debug 限制,排查 subagent 启动/结果链路用)。
|
|
27
|
+
* 写 <PYGMALION_DATA>/logs/meme-worker.log,每行带时间戳;PYGMALION_DATA 未设或写失败时静默跳过。
|
|
28
|
+
*/
|
|
29
|
+
export function memeTrace(scope, message) {
|
|
30
|
+
const root = process.env.PYGMALION_DATA;
|
|
31
|
+
if (!root) return;
|
|
32
|
+
try {
|
|
33
|
+
const dir = join(root, 'logs');
|
|
34
|
+
mkdirSync(dir, { recursive: true });
|
|
35
|
+
appendFileSync(join(dir, 'meme-worker.log'), `[${new Date().toISOString()}] [${scope}] ${message}\n`, 'utf8');
|
|
36
|
+
}
|
|
37
|
+
catch { /* 日志失败不影响主流程 */ }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 子代理输出预览(前 120 字),供 trace 使用。 */
|
|
41
|
+
function previewOutput(blocks) {
|
|
42
|
+
if (!Array.isArray(blocks)) return String(blocks ?? '(no output)');
|
|
43
|
+
const text = blocks.filter((b) => b?.type === 'text').map((b) => b.text).join('\n');
|
|
44
|
+
return text ? text.slice(0, 120) : `(no text, ${blocks.length} blocks)`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 解析某角色的视觉 provider/model(表情包子代理用)。优先级:
|
|
49
|
+
* 1. 显式 memeCollection.vision:配置了 model →
|
|
50
|
+
* - 配了 apiUrl/apiKey → 独立 route(pygmalion-meme-<roleId> 或显式 vision.provider);
|
|
51
|
+
* - 否则 → 显式 vision.provider 或内置 deepseek。
|
|
52
|
+
* 2. 角色主模型经 llm.resolveModelInfo 判定含 image → 复用(自定义 provider 常见场景)。
|
|
53
|
+
* 3. 兜底 DEFAULT_VISION。
|
|
54
|
+
* @param role 角色(loadRole 结果)
|
|
55
|
+
* @param opts { llm?, log? }
|
|
56
|
+
* @returns { provider, model }
|
|
57
|
+
*/
|
|
58
|
+
export async function resolveVisionConfig(role, { llm, log } = {}) {
|
|
59
|
+
const v = role?.proactive?.memeCollection?.vision ?? {};
|
|
60
|
+
const vModel = typeof v.model === 'string' && v.model.trim() ? v.model.trim() : '';
|
|
61
|
+
if (vModel) {
|
|
62
|
+
if (roleUsesCustomSubagentApi(role)) {
|
|
63
|
+
memeTrace('vision', `role ${role?.roleId} 显式视觉 API → ${memeVisionRoute(role)}/${vModel}`);
|
|
64
|
+
return { provider: memeVisionRoute(role), model: vModel };
|
|
65
|
+
}
|
|
66
|
+
const explicitProvider = typeof v.provider === 'string' && v.provider.trim() ? v.provider.trim() : '';
|
|
67
|
+
memeTrace('vision', `role ${role?.roleId} 显式 vision model → ${explicitProvider || DEFAULT_VISION.provider}/${vModel}`);
|
|
68
|
+
return { provider: explicitProvider || DEFAULT_VISION.provider, model: vModel };
|
|
69
|
+
}
|
|
70
|
+
const custom = roleUsesCustomProvider(role);
|
|
71
|
+
const provider = custom ? providerRoute(role) : DEFAULT_VISION.provider;
|
|
72
|
+
const mainModel = typeof role?.model?.model === 'string' ? role.model.model : '';
|
|
73
|
+
if (mainModel && llm && typeof llm.resolveModelInfo === 'function') {
|
|
74
|
+
try {
|
|
75
|
+
const info = await llm.resolveModelInfo(provider, mainModel);
|
|
76
|
+
if (info?.inputModalities?.includes('image') === true) {
|
|
77
|
+
memeTrace('vision', `role ${role?.roleId} 主模型 ${provider}/${mainModel} 含视觉 → 复用`);
|
|
78
|
+
return { provider, model: mainModel };
|
|
79
|
+
}
|
|
80
|
+
} catch { /* 判定失败走兜底 */ }
|
|
81
|
+
}
|
|
82
|
+
if (custom) {
|
|
83
|
+
log?.warn?.('pygmalion meme: 角色 %s 未配置 memeCollection.vision,视觉回退 %s/%s', role?.roleId, DEFAULT_VISION.provider, DEFAULT_VISION.model);
|
|
84
|
+
}
|
|
85
|
+
memeTrace('vision', `role ${role?.roleId} 兜底 → ${DEFAULT_VISION.provider}/${DEFAULT_VISION.model}`);
|
|
86
|
+
return { ...DEFAULT_VISION };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 按角色串行化表情包维护(定期 heartbeat 与委托 subagent_meme 互斥,不并发写库)。
|
|
91
|
+
* 进程内锁:同角色同时只允许一个 collect/classify 任务在跑。
|
|
92
|
+
*/
|
|
93
|
+
const memeLocks = new Map(); // roleId -> Promise
|
|
94
|
+
export function withMemeLock(roleId, fn) {
|
|
95
|
+
const key = roleId ?? 'default';
|
|
96
|
+
const prev = memeLocks.get(key) ?? Promise.resolve();
|
|
97
|
+
const run = prev.catch(() => {}).then(() => fn());
|
|
98
|
+
memeLocks.set(key, run);
|
|
99
|
+
return run.finally(() => { if (memeLocks.get(key) === run) memeLocks.delete(key); });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 识别提示词:给定一批本地图片路径,要求用 read_image 读取并判断「是否大众意义的表情包」+ 输出 JSON 数组。 */
|
|
103
|
+
export function buildClassifyPrompt(paths) {
|
|
104
|
+
return [
|
|
105
|
+
'你是 Pygmalion 的表情包识别助手。请用 read_image 依次读取下面的每一张图片。',
|
|
106
|
+
'对每张图,先判断它是不是「大众意义上的表情包/梗图」:有明确情绪或梗意、能当聊天表情用的图',
|
|
107
|
+
'(排除普通照片、emoji 图形、纯文字图、截图、二维码、商品图等非表情包)。',
|
|
108
|
+
'若是表情包,再识别内容(content)、风格(style)、适用语境(contexts);若不是,valid 设为 false。',
|
|
109
|
+
'只输出一个 JSON 数组(与图片顺序一一对应):',
|
|
110
|
+
'[{"valid":true,"content":"...","style":"...","contexts":["..."]}] 或 [{"valid":false}]',
|
|
111
|
+
'不要输出其它任何文字。',
|
|
112
|
+
'图片路径:',
|
|
113
|
+
...paths.map((p, i) => `${i + 1}. ${p}`),
|
|
114
|
+
].join('\n');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 收集目标(用户消息):只放目标与张数;流程/约束在系统提示词(buildCollectSystemPrompt)。 */
|
|
118
|
+
export function buildCollectGoal(goal, count) {
|
|
119
|
+
const target = count === undefined || count === null || count === ''
|
|
120
|
+
? '尽量多收集'
|
|
121
|
+
: (typeof count === 'number' ? `收集约 ${count} 张` : `收集 ${count} 张`);
|
|
122
|
+
return `目标:${goal || '为角色收集一组风格匹配、可直接下载的表情包图片'}。${target}。`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 收集约束(系统提示词):流程 + 数量硬约束(达到目标即停,超额合格也不存)+ 质量规则。 */
|
|
126
|
+
export function buildCollectSystemPrompt() {
|
|
127
|
+
return [
|
|
128
|
+
'你是 Pygmalion 的表情包收集助手(自主执行,不需要等待任何人的进一步指示)。',
|
|
129
|
+
'严格遵守用户消息里指定的目标张数:成功归档达到该数量后必须立即停止,',
|
|
130
|
+
'即使后面还有合格的表情包也不要再入库(只看不存);宁可少,绝不超额。',
|
|
131
|
+
'收集流程:',
|
|
132
|
+
'1. 首选 fabiaoqing.com(发表情)——国内、专供表情包、图片可直接下载。从目标提炼 2~3 个主题关键词,'
|
|
133
|
+
+ '构造搜索页 https://fabiaoqing.com/search/bqb/keyword/<关键词>/type/bq/page/<页码>.html'
|
|
134
|
+
+ '(关键词做 URL 编码;页码从 1 开始,每页约 19 张)。',
|
|
135
|
+
'2. 对每个搜索页调用 meme_download 传入【页面 URL】——它会批量抓取页内全部表情包图片并返回本地路径列表;'
|
|
136
|
+
+ '一页不够就翻 page/2、page/3,或换下一个关键词。',
|
|
137
|
+
'3. 备选来源:soogif.com 首页(GIF 表情包,img.soogif.com 直链可下);一般 fabiaoqing 即足够。',
|
|
138
|
+
'4. 对下载好的本地路径逐个调用 meme_archive 入库——它一步完成「看图判定 + 提取元数据 + 保存」,返回 memeId;'
|
|
139
|
+
+ '非表情包/失败自动跳过。每成功归档一张计一次数。',
|
|
140
|
+
'5. 达到目标数量立即停止归档(不再调用 meme_archive);其余下载但未归档的图片无需处理。',
|
|
141
|
+
'全部完成后,用一句话汇报实际收集了多少张。',
|
|
142
|
+
].join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 从子代理文本输出里提取 JSON 值(兼容「对象」与「数组」两种输出,返回对象数组)。
|
|
147
|
+
* 按最外层结构优先:若 `[` 先于 `{` 出现按数组解析,否则按对象解析(避免把对象里的 contexts:[..] 误当外层数组)。
|
|
148
|
+
*/
|
|
149
|
+
export function parseWorkerJsonArray(outputBlocks) {
|
|
150
|
+
const text = (outputBlocks ?? [])
|
|
151
|
+
.filter((b) => b.type === 'text')
|
|
152
|
+
.map((b) => b.text).join('\n');
|
|
153
|
+
const arrStart = text.indexOf('[');
|
|
154
|
+
const objStart = text.indexOf('{');
|
|
155
|
+
const parseBalanced = (startIdx, openChar, closeChar) => {
|
|
156
|
+
let depth = 0;
|
|
157
|
+
for (let i = startIdx; i < text.length; i++) {
|
|
158
|
+
if (text[i] === openChar) depth++;
|
|
159
|
+
else if (text[i] === closeChar) {
|
|
160
|
+
depth--;
|
|
161
|
+
if (depth === 0) {
|
|
162
|
+
try { return JSON.parse(text.slice(startIdx, i + 1)); } catch { return undefined; }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
};
|
|
168
|
+
if (arrStart >= 0 && (objStart < 0 || arrStart < objStart)) {
|
|
169
|
+
// 数组输出(归类/收集)——优先解析最外层 [..]
|
|
170
|
+
const arr = parseBalanced(arrStart, '[', ']');
|
|
171
|
+
if (Array.isArray(arr)) return arr.filter((x) => x && typeof x === 'object');
|
|
172
|
+
} else if (objStart >= 0) {
|
|
173
|
+
// 对象输出(读图/归档)——解析最外层 {..}
|
|
174
|
+
const obj = parseBalanced(objStart, '{', '}');
|
|
175
|
+
if (obj && typeof obj === 'object') return [obj];
|
|
176
|
+
}
|
|
177
|
+
return [];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** spawn 一个一次性 subagent(以 parentAgent 为父);vision = resolveVisionConfig 结果。
|
|
181
|
+
* opts.maxDepth 控制子代理可下钻深度:默认 1;嵌套场景(子代理里再起视觉子代理)传 2。
|
|
182
|
+
* opts.persona 作为子代理系统提示词(约束放这里);缺省用通用表情包助手提示词。
|
|
183
|
+
* 成功返回 run.result({ output, stopReason });失败返回 { ok:false, error }(附具体原因,供调用方透传)。 */
|
|
184
|
+
async function spawnWorker(subagents, parentAgent, promptText, vision, log, label, opts = {}) {
|
|
185
|
+
const maxDepth = opts.maxDepth ?? 1;
|
|
186
|
+
const persona = opts.persona ?? '你是 Pygmalion 的表情包识别/收集助手。严格按任务要求输出 JSON,不要调用除指定工具外的任何工具。';
|
|
187
|
+
memeTrace(label, `entry: subagents=${!!subagents} parent=${!!parentAgent} vision=${vision ? `${vision.provider}/${vision.model}` : 'none'} maxDepth=${maxDepth} prompt=${promptText.slice(0, 60).replace(/\n/g, ' ')}`);
|
|
188
|
+
if (!subagents || !parentAgent || !vision) {
|
|
189
|
+
memeTrace(label, `entry guard failed: subagents=${!!subagents} parent=${!!parentAgent} vision=${!!vision}`);
|
|
190
|
+
return { ok: false, error: 'subagent 上下文缺失(subagents/parent/vision)' };
|
|
191
|
+
}
|
|
192
|
+
const controller = new AbortController();
|
|
193
|
+
const timer = setTimeout(() => controller.abort(), WORKER_SIGNAL_TIMEOUT_MS);
|
|
194
|
+
try {
|
|
195
|
+
// 注意:不传 toolFilter —— web 运行时 web_search/read_image 属 preset 层而非 global 层,
|
|
196
|
+
// tools.restrict 对非 global 工具名直接抛错,会让 child 创建失败(见 .agent-presets 注释)。
|
|
197
|
+
// child 经 composeFrom 已继承导演 preset 的工具集,prompt 已限定只用相关工具。
|
|
198
|
+
memeTrace(label, `subagents.start('spawn') provider=${vision.provider} model=${vision.model} maxDepth=${maxDepth}`);
|
|
199
|
+
const run = await subagents.start('spawn', {
|
|
200
|
+
label,
|
|
201
|
+
prompt: [{ type: 'text', text: promptText }],
|
|
202
|
+
parent: parentAgent,
|
|
203
|
+
signal: controller.signal,
|
|
204
|
+
agentOptions: { provider: vision.provider, model: vision.model },
|
|
205
|
+
persona,
|
|
206
|
+
maxDepth,
|
|
207
|
+
});
|
|
208
|
+
memeTrace(label, `run started: id=${run?.id ?? '?'} hasResult=${typeof run?.result === 'object' || typeof run?.result === 'function'} hasDispose=${typeof run?.dispose === 'function'}`);
|
|
209
|
+
const result = await run.result;
|
|
210
|
+
memeTrace(label, `run.result: stopReason=${result?.stopReason ?? '?'} outputBlocks=${Array.isArray(result?.output) ? result.output.length : '?'} output=${previewOutput(result?.output)}`);
|
|
211
|
+
try { run.dispose?.(); } catch { /* 释放失败忽略 */ }
|
|
212
|
+
return result;
|
|
213
|
+
} catch (error) {
|
|
214
|
+
const detail = error instanceof Error ? `${error.message}\n ${(error.stack ?? '').split('\n').slice(1, 7).join('\n ')}` : String(error);
|
|
215
|
+
memeTrace(label, `spawn FAILED: ${detail}`);
|
|
216
|
+
log?.warn?.('pygmalion meme worker spawn failed (%s): %o', label, error);
|
|
217
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
218
|
+
} finally {
|
|
219
|
+
clearTimeout(timer);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 识别并归类某角色 workspace 下所有待归类(staging)表情包。
|
|
225
|
+
* @param deps - { subagents, parentAgent, workspace, vision, log }
|
|
226
|
+
* @returns { ok, classified, total }
|
|
227
|
+
*/
|
|
228
|
+
export async function classifyStagedMemes(deps) {
|
|
229
|
+
const { workspace, vision, log } = deps;
|
|
230
|
+
const staged = (await listMemes(workspace)).filter((m) => m.status === 'staging');
|
|
231
|
+
memeTrace('classify', `workspace=${workspace} staging=${staged.length}`);
|
|
232
|
+
if (staged.length === 0) return { ok: true, classified: 0, total: 0 };
|
|
233
|
+
const paths = [];
|
|
234
|
+
const byPath = new Map();
|
|
235
|
+
for (const m of staged) {
|
|
236
|
+
const p = await memeFileFor(workspace, m.id);
|
|
237
|
+
if (p) { paths.push(p); byPath.set(p, m.id); }
|
|
238
|
+
}
|
|
239
|
+
if (paths.length === 0) return { ok: true, classified: 0, total: staged.length };
|
|
240
|
+
const result = await spawnWorker(deps.subagents, deps.parentAgent, buildClassifyPrompt(paths), vision, log, 'pygmalion-meme-classify');
|
|
241
|
+
if (!result || result.ok === false) return { ok: false, classified: 0, total: staged.length, error: result?.error ?? 'subagent 不可用或启动失败' };
|
|
242
|
+
const items = parseWorkerJsonArray(result.output);
|
|
243
|
+
memeTrace('classify', `subagent parsed items=${items.length} / paths=${paths.length} output=${previewOutput(result.output)}`);
|
|
244
|
+
let classified = 0;
|
|
245
|
+
let removed = 0;
|
|
246
|
+
for (let i = 0; i < items.length && i < paths.length; i++) {
|
|
247
|
+
const item = items[i];
|
|
248
|
+
const id = byPath.get(paths[i]);
|
|
249
|
+
if (!id || !item) continue;
|
|
250
|
+
// 非大众意义的表情包(普通照片/emoji 图/截图/二维码等)→ 从库中删除,不归档。
|
|
251
|
+
if (item.valid === false) {
|
|
252
|
+
const r = await deleteMeme(workspace, id);
|
|
253
|
+
if (r.ok) removed++;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const r = await updateMeme(workspace, id, {
|
|
257
|
+
content: typeof item.content === 'string' ? item.content : '',
|
|
258
|
+
style: typeof item.style === 'string' ? item.style : '',
|
|
259
|
+
contexts: Array.isArray(item.contexts) ? item.contexts.filter((s) => typeof s === 'string') : [],
|
|
260
|
+
});
|
|
261
|
+
if (r.ok) classified++;
|
|
262
|
+
}
|
|
263
|
+
log?.info?.('pygmalion meme classify: %d classified, %d removed (not memes), %d staged total', classified, removed, staged.length);
|
|
264
|
+
memeTrace('classify', `done: classified=${classified} removed=${removed} total=${staged.length}`);
|
|
265
|
+
return { ok: true, classified, removed, total: staged.length };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* 周期/委托收集:子代理自主「fabiaoqing 找候选 → meme_download 下载 → meme_archive 原子归档」,
|
|
270
|
+
* 插件只负责等待结果、计算本次新增(before/after 差)并清理临时下载目录。入库即 ready,主 agent 可直接 meme_find/meme_send。
|
|
271
|
+
* @param deps - { subagents, parentAgent, workspace, vision, goal?, count?, log } count 为目标张数(number 或 '5~10')
|
|
272
|
+
* @returns { ok, collected } collected = 本次新增已归档(ready)的表情包数
|
|
273
|
+
*/
|
|
274
|
+
export async function collectMemes(deps) {
|
|
275
|
+
const { workspace, vision, goal, count, log } = deps;
|
|
276
|
+
memeTrace('collect', `workspace=${workspace} goal=${goal ?? '(none)'} count=${count ?? '(默认)'} vision=${vision ? `${vision.provider}/${vision.model}` : 'none'}`);
|
|
277
|
+
const before = new Set((await listMemes(workspace)).filter((m) => m.status === 'ready').map((m) => m.id));
|
|
278
|
+
const result = await spawnWorker(deps.subagents, deps.parentAgent, buildCollectGoal(goal, count), vision, log, 'pygmalion-meme-collect', { persona: buildCollectSystemPrompt() });
|
|
279
|
+
// 清理 meme_download 留下的临时收集目录(无论成功失败)。
|
|
280
|
+
await rm(join(workspace, '.meme-collect'), { recursive: true, force: true }).catch(() => {});
|
|
281
|
+
if (!result || result.ok === false) {
|
|
282
|
+
memeTrace('collect', `spawnWorker failed: ${result?.error ?? 'subagent 不可用或启动失败'}`);
|
|
283
|
+
return { ok: false, collected: 0, error: result?.error ?? 'subagent 不可用或启动失败' };
|
|
284
|
+
}
|
|
285
|
+
const ready = (await listMemes(workspace)).filter((m) => m.status === 'ready');
|
|
286
|
+
const added = ready.filter((m) => !before.has(m.id)).length;
|
|
287
|
+
memeTrace('collect', `done: subagent output=${previewOutput(result.output)} added=${added}`);
|
|
288
|
+
log?.info?.('pygmalion meme collect: 子代理收集 %d 张(%s)', added, goal ?? '(default)');
|
|
289
|
+
return { ok: true, collected: added };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 收集 + 归类一气呵成(委托 subagent_meme 与 heartbeat 定期共用同一管线):
|
|
294
|
+
* 先按 goal 收集(web_search → 插件下载落 staging),再统一识别归类(read_image → 插件写库)。
|
|
295
|
+
* @param deps - { subagents, parentAgent, workspace, vision, log }
|
|
296
|
+
* @param opts - { goal?, count? }
|
|
297
|
+
* @returns { ok, collected, classified, removed, memeIds[] } memeIds = 本次新增且已归档(ready)的 id
|
|
298
|
+
*/
|
|
299
|
+
export async function collectAndClassify(deps, { goal, count } = {}) {
|
|
300
|
+
const { workspace, vision } = deps;
|
|
301
|
+
// 注意:vision 只从 deps 取。若在第二个参数里再解构 vision,调用方(subagent_meme)只把它放 deps、
|
|
302
|
+
// 不放 opts 时,`{ ...deps, vision, goal }` 会用 undefined 覆盖 deps.vision → spawn 拿不到视觉配置。
|
|
303
|
+
memeTrace('collectAndClassify', `goal=${goal ?? '(none)'} count=${count ?? '(默认)'} vision=${vision ? `${vision.provider}/${vision.model}` : 'none'}`);
|
|
304
|
+
const before = new Set((await listMemes(workspace)).filter((m) => m.status === 'ready').map((m) => m.id));
|
|
305
|
+
const collect = goal
|
|
306
|
+
? await collectMemes({ ...deps, goal, count })
|
|
307
|
+
: { collected: 0 };
|
|
308
|
+
// 收集失败必须如实上报,不能伪装成「收集 0 张」(subagent_meme 的 render 会展示 error)。
|
|
309
|
+
if (collect?.ok === false) {
|
|
310
|
+
memeTrace('collectAndClassify', `collect failed: ${collect?.error ?? '?'}`);
|
|
311
|
+
return { ok: false, collected: 0, classified: 0, removed: 0, memeIds: [], error: collect?.error ?? '收集失败' };
|
|
312
|
+
}
|
|
313
|
+
const classify = await classifyStagedMemes({ ...deps });
|
|
314
|
+
if (classify?.ok === false) {
|
|
315
|
+
memeTrace('collectAndClassify', `classify failed: ${classify?.error ?? '?'}`);
|
|
316
|
+
return { ok: false, collected: collect?.collected ?? 0, classified: 0, removed: 0, memeIds: [], error: classify?.error ?? '归类失败' };
|
|
317
|
+
}
|
|
318
|
+
const ready = (await listMemes(workspace)).filter((m) => m.status === 'ready');
|
|
319
|
+
const added = ready.filter((m) => !before.has(m.id)).map((m) => m.id);
|
|
320
|
+
memeTrace('collectAndClassify', `done: collected=${collect?.collected ?? 0} classified=${classify?.classified ?? 0} removed=${classify?.removed ?? 0} added=${added.length}`);
|
|
321
|
+
return {
|
|
322
|
+
ok: true,
|
|
323
|
+
collected: collect?.collected ?? 0,
|
|
324
|
+
classified: classify?.classified ?? 0,
|
|
325
|
+
removed: classify?.removed ?? 0,
|
|
326
|
+
memeIds: added,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** 阅读提示词:主 agent 无视觉时经视觉子代理看图,返回内容/风格/语境描述。 */
|
|
331
|
+
export function buildReadPrompt(path) {
|
|
332
|
+
return [
|
|
333
|
+
'你是 Pygmalion 的看图助手。用 read_image 读取这张图片,简洁描述它的内容(content)、',
|
|
334
|
+
'风格(style)、适用语境(contexts)。只输出一个 JSON 对象:',
|
|
335
|
+
'{"content":"...","style":"...","contexts":["..."]}',
|
|
336
|
+
'不要输出其它任何文字。',
|
|
337
|
+
`图片路径:${path}`,
|
|
338
|
+
].join('\n');
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* 经视觉子代理读一张图(主 agent 无视觉时的「阅读」能力)。
|
|
343
|
+
* @param deps - { subagents, parentAgent, log }
|
|
344
|
+
* @param opts - { file, vision }
|
|
345
|
+
* @returns { ok, content, style, contexts } 或 { ok:false, error }
|
|
346
|
+
*/
|
|
347
|
+
export async function readImageBySubagent(deps, { file, vision }) {
|
|
348
|
+
memeTrace('read', `file=${file} vision=${vision ? `${vision.provider}/${vision.model}` : 'none'}`);
|
|
349
|
+
const result = await spawnWorker(deps.subagents, deps.parentAgent, buildReadPrompt(file), vision, deps.log, 'pygmalion-meme-read');
|
|
350
|
+
if (!result || result.ok === false) return { ok: false, error: result?.error ?? 'subagent 不可用或启动失败' };
|
|
351
|
+
const items = parseWorkerJsonArray(result.output);
|
|
352
|
+
memeTrace('read', `parsed items=${items.length} output=${previewOutput(result.output)}`);
|
|
353
|
+
const item = items[0];
|
|
354
|
+
if (!item || typeof item !== 'object') return { ok: false, error: 'subagent 未返回有效描述' };
|
|
355
|
+
return {
|
|
356
|
+
ok: true,
|
|
357
|
+
content: typeof item.content === 'string' ? item.content : '',
|
|
358
|
+
style: typeof item.style === 'string' ? item.style : '',
|
|
359
|
+
contexts: Array.isArray(item.contexts) ? item.contexts.filter((s) => typeof s === 'string') : [],
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 归档判定提示词:判断是否合格表情包 + 提取元数据(meme_archive 工具用,读图与入库原子绑定,杜绝张冠李戴)。 */
|
|
364
|
+
export function buildArchivePrompt(path) {
|
|
365
|
+
return [
|
|
366
|
+
'你是 Pygmalion 的表情包识别助手。用 read_image 读取这张图片,判断它是不是「大众意义上的表情包/梗图」'
|
|
367
|
+
+ '(有明确情绪或梗意、能当聊天表情用;排除普通照片、emoji 图形、纯文字图、截图、二维码、商品图等)。',
|
|
368
|
+
'若是表情包,只输出一个 JSON 对象:{"valid":true,"content":"...","style":"...","contexts":["..."]}',
|
|
369
|
+
'若不是,只输出:{"valid":false}。不要输出其它任何文字。',
|
|
370
|
+
`图片路径:${path}`,
|
|
371
|
+
].join('\n');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* 经视觉子代理读一张图并判定(meme_archive 用):原子「看图判定 + 提取元数据」,返回 valid/content/style/contexts。
|
|
376
|
+
* maxDepth=2:meme_archive 可能被收集子代理(depth 1)调用,其视觉子代理在 depth 2。
|
|
377
|
+
* @param deps - { subagents, parentAgent, log }
|
|
378
|
+
* @param opts - { file, vision }
|
|
379
|
+
* @returns { ok, valid, content, style, contexts } 或 { ok:false, error }
|
|
380
|
+
*/
|
|
381
|
+
export async function archiveImageBySubagent(deps, { file, vision }) {
|
|
382
|
+
memeTrace('archive', `file=${file} vision=${vision ? `${vision.provider}/${vision.model}` : 'none'}`);
|
|
383
|
+
const result = await spawnWorker(deps.subagents, deps.parentAgent, buildArchivePrompt(file), vision, deps.log, 'pygmalion-meme-archive', { maxDepth: 2 });
|
|
384
|
+
if (!result || result.ok === false) return { ok: false, error: result?.error ?? 'subagent 不可用或启动失败' };
|
|
385
|
+
const items = parseWorkerJsonArray(result.output);
|
|
386
|
+
memeTrace('archive', `parsed items=${items.length} output=${previewOutput(result.output)}`);
|
|
387
|
+
const item = items[0];
|
|
388
|
+
if (!item || typeof item !== 'object') return { ok: false, error: 'subagent 未返回有效判定' };
|
|
389
|
+
if (item.valid === false) return { ok: false, valid: false, error: '非表情包' };
|
|
390
|
+
return {
|
|
391
|
+
ok: true,
|
|
392
|
+
valid: true,
|
|
393
|
+
content: typeof item.content === 'string' ? item.content : '',
|
|
394
|
+
style: typeof item.style === 'string' ? item.style : '',
|
|
395
|
+
contexts: Array.isArray(item.contexts) ? item.contexts.filter((s) => typeof s === 'string') : [],
|
|
396
|
+
};
|
|
397
|
+
}
|