dsh-wechat-access 0.0.0-stage → 0.0.2

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
package/lib/tools.mjs ADDED
@@ -0,0 +1,583 @@
1
+ import { allowConversation } from './config.mjs';
2
+ import { assert, checkSignal, combinedSignal, integer, peerId as toPeerId, requestId, textArg, noteLog } from './util.mjs';
3
+ import { hhmmOf } from './virtual-life.mjs';
4
+
5
+ const string = description => ({ type: 'string', description });
6
+ const enumeration = values => ({ type: 'string', enum: values });
7
+ const target = { kind: enumeration(['private', 'group']), peer_id: string('会话 ID:单聊填对方微信号或 wxid_xxx,群聊填 xxx@chatroom') };
8
+
9
+ // 未连接(守护进程没起来 / 掉线)时仍然可用的工具。
10
+ // 这些不依赖微信连接:查本地归档、读日程、抓网页、收集表情、查资料。
11
+ const OFFLINE_TOOLS = new Set([
12
+ 'wx_meme_collect',
13
+ 'wx_web_search',
14
+ 'wx_web_extract',
15
+ 'wx_web_batch',
16
+ 'wx_life_status',
17
+ 'wx_life_generate',
18
+ 'wx_steam_status',
19
+ 'wx_endocrine',
20
+ ]);
21
+
22
+ export function makeTools(runtime) {
23
+ const { access, config } = runtime;
24
+ const definitions = [];
25
+ const tool = (name, description, properties, required, execute) => {
26
+ definitions.push({
27
+ name, description,
28
+ parameters: { type: 'object', properties, required, additionalProperties: false },
29
+ output: {
30
+ schema: { type: 'object', additionalProperties: true },
31
+ render: (_args, value) => {
32
+ // Tool results can carry image blocks; the model only sees what render emits,
33
+ // so pass them through instead of flattening everything into JSON text.
34
+ const attachments = Array.isArray(value?.content)
35
+ ? value.content.filter(part => part && part.type === 'image' && part.attachment)
36
+ : [];
37
+ const rest = attachments.length ? { ...value, content: undefined } : value;
38
+ const text = { type: 'text', text: JSON.stringify(rest) };
39
+ return attachments.length ? [text, ...attachments] : [text];
40
+ },
41
+ },
42
+ execute: async (args, exec) => {
43
+ assert(args && typeof args === 'object' && !Array.isArray(args), '工具参数必须为对象');
44
+ for (const key of required) assert(args[key] !== undefined, `缺少参数 ${key}`);
45
+ for (const key of Object.keys(args)) assert(Object.hasOwn(properties, key), `未知参数 ${key}`);
46
+ const denied = access.guard({ ...exec, name });
47
+ assert(!denied, denied);
48
+ checkSignal(exec.signal);
49
+ // exec.signal is optional: AbortSignal.any() throws on a non-signal entry, so
50
+ // filter first. Without this, any call that omits a signal fails before the
51
+ // tool body ever runs.
52
+ const signals = [exec.signal, runtime.shutdown.signal].filter((s) => s && typeof s.addEventListener === 'function');
53
+ const signal = signals.length > 1 ? AbortSignal.any(signals) : (signals[0] ?? new AbortController().signal);
54
+ // 每个工具的墙钟预算。
55
+ //
56
+ // B11:生图自己的超时默认就有 120 秒,而这里以前给所有工具
57
+ // 一律 120 秒 —— 生图一慢就把整个预算吃光,后面「把图发出去」那一步
58
+ // 面对的是一个已经 abort 的信号,用户看到的是「拍好了但没发出去」,
59
+ // 日志里只有一句取消,看不出是预算不够。
60
+ // 所以生图的预算必须比它自己的超时更大,留出下载/上传/发送的余量。
61
+ const imageTimeoutMs = Number(config.image?.timeoutMs ?? 120_000);
62
+ const budgetFor = (toolName) => {
63
+ if (toolName === 'wx_generate_image') return Math.max(150_000, imageTimeoutMs + 30_000);
64
+ return 120_000;
65
+ };
66
+ // 外层不能一刀切。
67
+ // 以前这里固定 allowOffline: name === 'wx_status',把内层工具自己声明的
68
+ // allowOffline: true 全部盖掉 —— 等待连接期间模型连网页搜索、日程、表情收集
69
+ // 都用不了,而面板上同样的按钮却能用(面板不走工具表)。
70
+ return runtime.runTool(
71
+ () => execute(args, { ...exec, signal: combinedSignal(signal, budgetFor(name)) }),
72
+ { allowOffline: name === 'wx_status' || OFFLINE_TOOLS.has(name), allowClosed: name === 'wx_status' },
73
+ );
74
+ },
75
+ });
76
+ };
77
+
78
+ tool('wx_status', '查看微信接入状态。普通会话只可见本会话状态。', {}, [], async (_args, exec) => runtime.status(exec.agent));
79
+
80
+ tool('wx_list_contacts', '列出当前微信账号的好友或群。仅本机 Harness / 管理员私聊可调用。返回 wxid 用于后续操作。', {
81
+ kind: enumeration(['friends', 'groups']), offset: { type: 'integer' }, limit: { type: 'integer' },
82
+ }, ['kind'], async (args, exec) => {
83
+ access.requireManager(exec.agent);
84
+ const limit = Math.min(200, Math.max(1, Number(args.limit) || 50));
85
+ if (args.kind === 'groups') {
86
+ const page = await runtime.client.groups({ limit, signal: exec.signal });
87
+ return { groups: (page.items ?? []).map(g => ({ id: String(g.id), name: String(g.displayName ?? '') })) };
88
+ }
89
+ const page = await runtime.client.contacts({ limit, signal: exec.signal });
90
+ return { contacts: (page.items ?? []).map(c => ({ id: String(c.id), name: String(c.displayName ?? '') })) };
91
+ });
92
+
93
+ tool('wx_list_conversations', '列出本插件已归档的最近会话;从开始运行后累积,不代表微信全部历史。', {
94
+ limit: { type: 'integer' }, offset: { type: 'integer' },
95
+ }, [], async (args, exec) => {
96
+ access.requireManager(exec.agent);
97
+ const all = runtime.store.conversations?.() ?? [];
98
+ const offset = Math.max(0, Number(args.offset) || 0);
99
+ const limit = Math.min(100, Math.max(1, Number(args.limit) || 20));
100
+ return { total: all.length, conversations: all.slice(offset, offset + limit) };
101
+ });
102
+
103
+ tool('wx_read_history', '读取一个会话的最近消息。source=local 读本地归档;source=wechat 调用微信接口。', {
104
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'),
105
+ count: { type: 'integer' }, before_seq: string('微信接口的分页游标'),
106
+ source: enumeration(['local', 'wechat']),
107
+ }, ['kind', 'peer_id'], async (args, exec) => {
108
+ const peer = toPeerId(args.peer_id);
109
+ const count = Math.min(200, Math.max(1, Number(args.count) || 20));
110
+ if (args.source === 'wechat') {
111
+ const page = await runtime.client.messages(peer, { limit: count, signal: exec.signal });
112
+ return { messages: (page.items ?? []).map(m => ({
113
+ id: String(m.id), serverId: m.serverId, direction: m.direction,
114
+ senderId: m.senderId, text: String(m.body ?? ''), type: Number(m.type),
115
+ at: m.createdAt,
116
+ })) };
117
+ }
118
+ const result = await runtime.store.query({ kind: args.kind, peerId: peer, limit: count });
119
+ return { messages: result.messages ?? [] };
120
+ });
121
+
122
+ tool('wx_search_messages', '按关键词搜索本地归档的一个指定会话,返回保留期内最近的匹配记录。', {
123
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'), keyword: string('要搜索的原文关键词'), count: { type: 'integer' },
124
+ }, ['kind', 'peer_id', 'keyword'], async (args, exec) => {
125
+ const peer = toPeerId(args.peer_id);
126
+ const r = await runtime.store.search({ kind: args.kind, peerId: peer, keyword: args.keyword, limit: Math.min(100, Number(args.count) || 20) });
127
+ return r;
128
+ });
129
+
130
+ tool('wx_send_message', '向指定私聊或群聊发送文本。request_id 是本次操作的唯一标识;重试同一操作必须复用它。', {
131
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'), text: string('完整消息正文'),
132
+ mentions: { type: 'array', items: { type: 'string' }, description: '群聊中要 @ 的成员 ID;["all"] 表示 @全体' },
133
+ request_id: string('8–160 位唯一操作标识;重试复用'),
134
+ }, ['kind', 'peer_id', 'text', 'request_id'], async (args, exec) => {
135
+ const peer = toPeerId(args.peer_id);
136
+ const rid = requestId(args.request_id);
137
+ if (String(args.mentions ?? '').includes('all')) access.requireManager(exec.agent);
138
+ return runtime.sendText(args.kind, peer, args.text, rid, exec.signal, args.mentions ?? []);
139
+ });
140
+
141
+ tool('wx_send_image', '发送一张图片。source 可以是本地绝对路径、http(s) URL、data:image/... 或 base64:// 内容。', {
142
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'), source: string('图片来源'),
143
+ caption: string('图片后附带的一句话'), request_id: string('唯一操作标识'),
144
+ }, ['kind', 'peer_id', 'source', 'request_id'], async (args, exec) => {
145
+ const peer = toPeerId(args.peer_id);
146
+ return runtime.sendImage(args.kind, peer, args.source, requestId(args.request_id), exec.signal, [], String(args.caption ?? ''));
147
+ });
148
+
149
+ tool('wx_recall_message', '撤回本账号发出的一条消息(2 分钟内)。message_id 省略时撤回本会话最近一条自己发的消息。', {
150
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'), message_id: string('要撤回的消息 ID'),
151
+ }, ['kind', 'peer_id'], async (args, exec) => {
152
+ const peer = toPeerId(args.peer_id);
153
+ return runtime.recallMessage(args.kind, peer, args.message_id, exec.signal);
154
+ });
155
+
156
+ tool('wx_get_message', '按 message_id 取一条消息的完整内容,包括图片。', {
157
+ kind: enumeration(['private', 'group']), peer_id: string('会话 ID'), message_id: string('消息 ID'),
158
+ }, ['kind', 'peer_id', 'message_id'], async (args, exec) => {
159
+ const peer = toPeerId(args.peer_id);
160
+ return runtime.getMessage(args.kind, peer, args.message_id, exec.signal);
161
+ });
162
+
163
+ tool('wx_get_user_info', '查询一个微信联系人的公开资料(昵称、备注、微信号)。', {
164
+ user_id: string('联系人 ID(wxid_xxx 或自定义微信号)'),
165
+ }, ['user_id'], async (args, exec) => {
166
+ const id = toPeerId(args.user_id);
167
+ const c = await runtime.client.contact(id, exec.signal);
168
+ return { id: String(c?.id ?? id), name: String(c?.displayName ?? ''), nickname: c?.nickname ?? null, alias: c?.alias ?? null };
169
+ });
170
+
171
+ tool('wx_get_avatar', '获取一个联系人的头像。返回图片,模型可以直接看到。', {
172
+ user_id: string('联系人 ID'),
173
+ }, ['user_id'], async (args, exec) => {
174
+ const id = toPeerId(args.user_id);
175
+ const response = await runtime.client.avatar(id, exec.signal);
176
+ const bytes = new Uint8Array(await response.arrayBuffer());
177
+ const mediaType = response.headers.get('content-type') || 'image/jpeg';
178
+ const attachments = runtime.ctx.get?.('attachments');
179
+ if (!attachments) return { ok: false, error: '宿主未提供附件服务' };
180
+ const ref = await attachments.saveImage({ data: bytes, mediaType, name: 'wechat-avatar' });
181
+ return { ok: true, content: [{ type: 'image', attachment: ref }] };
182
+ });
183
+
184
+ tool('wx_get_group_members', '列出群成员(群昵称、昵称、角色)。', {
185
+ group_id: string('群 ID(xxx@chatroom)'), limit: { type: 'integer' }, search: string('按名字搜索'),
186
+ }, ['group_id'], async (args, exec) => {
187
+ const gid = toPeerId(args.group_id);
188
+ if (!gid.endsWith('@chatroom')) return { ok: false, error: '不是一个群 ID' };
189
+ const page = await runtime.client.groupMembers(gid, { limit: Math.min(200, Number(args.limit) || 50), search: args.search, signal: exec.signal });
190
+ return { members: (page.items ?? []).map(m => ({ id: String(m.id ?? ''), name: String(m.displayName ?? ''), role: m.role ?? null })) };
191
+ });
192
+
193
+ tool('wx_group_member_info', '读取群成员资料;不传 user_id 时返回本账号在该群的资料,用于确认自己的群昵称。', {
194
+ group_id: string('群 ID'), user_id: string('要查询的成员 ID;留空表示本账号'),
195
+ }, ['group_id'], async (args, exec) => {
196
+ const gid = toPeerId(args.group_id);
197
+ const uid = args.user_id ? toPeerId(args.user_id) : runtime.config.selfId;
198
+ const r = await runtime.client.groupMember(gid, uid, exec.signal);
199
+ return r;
200
+ });
201
+
202
+ tool('wx_generate_image', '拍一张照片发给他。你想让他看见你眼前的东西(你在吃什么、穿什么、在哪里、天气怎么样)、想给他看一个画面、对方让你发照片时用。拍一张要等十几秒,不要每句话都拍。', {
203
+ ...target,
204
+ prompt: string('照片里有什么:主体、动作、场景、光线、氛围。写具体一点,不要只写两个词。'),
205
+ style: string('可选:风格描述,如「水墨」「赛博朋克」「写实摄影」「动漫」'),
206
+ aspect_ratio: string('可选:画面比例,如 1:1 / 16:9 / 9:16 / 4:3 / 3:4'),
207
+ caption: string('可选:图后附带的一句话;不填就不说话,只发图'),
208
+ request_id: string('8–160 位唯一操作标识;重试复用'),
209
+ }, ['kind', 'peer_id', 'prompt', 'request_id'], async (args, exec) => {
210
+ access.requireManager(exec.agent);
211
+ const { kind, peerId } = access.target(args, exec.agent, { management: true });
212
+ const prompt = textArg(args.prompt, '画面描述', 1200);
213
+ const style = args.style === undefined ? '' : textArg(args.style, '风格', 80);
214
+ const aspectRatio = args.aspect_ratio === undefined ? '' : textArg(args.aspect_ratio, '比例', 10);
215
+ const caption = args.caption === undefined ? '' : textArg(args.caption, '图片说明', 300);
216
+ const id = requestId(args.request_id);
217
+ const result = await runtime.generateImageFor(
218
+ { kind, peerId, senderId: String(exec.agent?.wechatAccess?.senderId ?? '') },
219
+ { prompt, style, aspectRatio, signal: exec.signal },
220
+ );
221
+ if (!result.ok) return result;
222
+ // 图已经生成,接下来要真的发出去。
223
+ // 每张图用同一个 request_id 的序号后缀,重试时仍能幂等。
224
+ const sent = [];
225
+ for (const [index, image] of result.images.entries()) {
226
+ try {
227
+ // 两种形状:模型给 Markdown 链接时是下载好的 dataUrl;
228
+ // 模型给 image block 时是 attachment 路径,原样交给发送层。
229
+ const source = image.dataUrl || image.source;
230
+ if (!source) continue;
231
+ const receipt = await runtime.sendImage(
232
+ kind, peerId, source,
233
+ id + '-' + index,
234
+ exec.signal, [],
235
+ index === 0 ? caption : '',
236
+ );
237
+ sent.push({ index, messageId: receipt?.messageId ?? null });
238
+ } catch (error) {
239
+ noteLog('生图发送失败 ' + String(error?.message ?? error).slice(0, 160));
240
+ }
241
+ }
242
+ if (!sent.length) {
243
+ return { ok: false, reason: 'send_failed', message: '图生成了但发送失败。', generated: result.images.length };
244
+ }
245
+ return {
246
+ ok: true,
247
+ sent: sent.length,
248
+ generated: result.images.length,
249
+ hint: result.text || undefined,
250
+ };
251
+ });
252
+
253
+ tool('wx_meme_send', '发送一张表情包。id 来自 wx_meme_search。', {
254
+ ...target,
255
+ id: string('表情包 id'),
256
+ request_id: string('8–160 位唯一操作标识;重试必须复用'),
257
+ }, ['kind', 'peer_id', 'id', 'request_id'], async (args, exec) => runtime.runTool(async () => {
258
+ const lib = runtime.memes;
259
+ if (!lib) throw new Error('表情包图库未启用');
260
+ const entry = lib.entries.find((e) => e.id === String(args.id));
261
+ if (!entry) throw new Error('图库里没有这个 id');
262
+ // 走和 wx_send_message 相同的访问校验:黑名单里的群/人不该因为换了个工具就绕过去。
263
+ // 这里以前把 kind 和 peer 两个值直接当参数传给了 target —— 但它要的是整个 args
264
+ // 整个 args 对象(它内部读 args.kind、args.peer_id),传字符串进去会抛
265
+ // 「kind 必须为 private 或 group」。而自动配图走 sendImage 不经过这个工具,
266
+ // 所以只有「模型主动挑一张发」这条路径是坏的,很难被发现。
267
+ const { kind, peerId: peer } = access.target(args, exec.agent, { management: true });
268
+ const entryRecord = await runtime.sendImage(
269
+ args.kind, peer, lib.pathOf(entry),
270
+ requestId(args.request_id), exec.signal, [],
271
+ );
272
+ // ActionLedger.run() 返回的是账本记录,真正的 message_id 在 result.result 里。
273
+ // 以前读 result.messageId(永远是 undefined),而且不管 status 一律报 sent ——
274
+ // 账本返回 failed / uncertain / pending 时,模型会告诉对方表情已经发出去了。
275
+ const status = entryRecord?.status ?? 'sent';
276
+ const messageId = entryRecord?.result?.messageId;
277
+ if (status !== 'sent') {
278
+ return {
279
+ status,
280
+ ...(messageId ? { messageId } : {}),
281
+ id: entry.id,
282
+ note: status === 'uncertain'
283
+ ? '不确定是否已送达,不要重发;先确认对方的反应。'
284
+ : '没有发送成功,可以把情况如实说明。',
285
+ };
286
+ }
287
+ await lib.markUsed(entry.id);
288
+ return { status: 'sent', ...(messageId ? { messageId } : {}), id: entry.id };
289
+ }, { allowOffline: false }));
290
+
291
+
292
+ tool('wx_endocrine', '查看或调整你自己的内分泌与身体状态。仅管理员私聊可用;只影响语气和精力,不参与权限、拒绝或安全判定。', {
293
+ action: enumeration(['status', 'preview', 'push', 'inject', 'drug', 'scenario', 'trigger', 'relief', 'cure', 'cycle', 'cycleAdvance', 'cycleSet', 'cycleReset', 'mood', 'moodClear', 'mental', 'mentalClear']),
294
+ hormone: string('激素 id,如 cortisol / melatonin / estradiol'),
295
+ delta: { type: 'number', description: '变化量;push -80..80,inject -60..60' },
296
+ drug: string('药物 id,如 coffee / melatonin / ibuprofen'),
297
+ name: string('场景 id:stayUp / scare / full / calm'),
298
+ disease: string('疾病 slug,如 dsh-insomnia'),
299
+ relief: string('缓解项 id'),
300
+ day: { type: 'integer', description: '周期第几天' },
301
+ n: { type: 'integer', description: '周期推进天数' },
302
+ mood: string('心情 id'),
303
+ label: string('心情中文标签'),
304
+ intensity: { type: 'number', description: '心情强度 0..100' },
305
+ load: { type: 'number', description: '精神负荷 0..100' },
306
+ protect: { type: 'number', description: '保护值 0..100' },
307
+ sensitization: { type: 'number', description: '敏化 0..100' },
308
+ state: string('精神状态:none / depressive / anxiety / psychosis'),
309
+ }, ['action'], async (args, exec) => {
310
+ access.requireManager(exec.agent);
311
+ if (!runtime.endocrine) return { ok: false, error: '内分泌模块未启用' };
312
+ const out = await runtime.endocrine.action(args);
313
+ if (!out?.ok) return out;
314
+ const panel = await runtime.endocrine.panelState();
315
+ return { ...out, endocrine: panel.snapshot };
316
+ });
317
+
318
+ tool('wx_emotion_status', '查看某个联系人当前的情感状态:好感度、亲密度、关系阶段、八维情绪和最近的重要记忆。留空 peer_id 表示查询本会话的人。', {
319
+ peer_id: string('要查询的联系人 ID;留空表示本会话的对方'),
320
+ }, [], async (args, exec) => {
321
+ const store = runtime.emotion;
322
+ assert(store, '情感系统未启用');
323
+ await store.init();
324
+ const origin = runtime.access.originOf(exec.agent);
325
+ const target = args.peer_id
326
+ ? toPeerId(args.peer_id)
327
+ : (origin?.peerId ?? runtime.config.ownerIds[0] ?? '');
328
+ assert(target, '无法确定要查询的联系人');
329
+ // 非管理员只能看自己的;跨人查询需要管理员私聊或本机。
330
+ runtime.access.requireManager(exec.agent);
331
+ const key = store.keyFor({ peerId: target, kind: 'private' });
332
+ const { state, stage } = store.describe(key);
333
+ return {
334
+ peer_id: target,
335
+ favor: state.favor,
336
+ intimacy: state.intimacy,
337
+ stage: stage.stageName,
338
+ description: stage.description,
339
+ negative: stage.negative,
340
+ transitioning: stage.isTransitioning,
341
+ composite: Number(stage.composite.toFixed(1)),
342
+ emotions: { ...state.emotions },
343
+ attitude: state.attitude,
344
+ relationship: state.relationship,
345
+ totalTurns: state.totalTurns,
346
+ memories: (state.memories ?? []).slice(-5).map(m => ({ at: m.at, note: m.note, stage: m.stage })),
347
+ };
348
+ });
349
+
350
+
351
+ tool('wx_emotion_adjust', '直接设置某个联系人的好感度或亲密度。仅管理员私聊可用。用于纠正明显不准的数值。', {
352
+ peer_id: string('目标联系人 ID'),
353
+ favor: { type: 'integer', description: '好感度 -100 到 100' },
354
+ intimacy: { type: 'integer', description: '亲密度 0 到 100' },
355
+ }, ['peer_id'], async (args, exec) => {
356
+ const store = runtime.emotion;
357
+ assert(store, '情感系统未启用');
358
+ access.requireManager(exec.agent);
359
+ await store.init();
360
+ const target = toPeerId(args.peer_id);
361
+ const patch = {};
362
+ if (args.favor !== undefined) patch.favor = integer(args.favor, 0, -100, 100, '好感度');
363
+ if (args.intimacy !== undefined) patch.intimacy = integer(args.intimacy, 0, 0, 100, '亲密度');
364
+ assert(Object.keys(patch).length, '至少提供 favor 或 intimacy 之一');
365
+ const key = store.keyFor({ peerId: target, kind: 'private' });
366
+ const { state, stage } = await store.set(key, patch);
367
+ return { peer_id: target, favor: state.favor, intimacy: state.intimacy, stage: stage.stageName };
368
+ });
369
+
370
+
371
+ tool('wx_memory_status', '查看某个联系人被你记住的事情:长期事实和相关事件。留空 peer_id 表示本会话的对方。', {
372
+ peer_id: string('要查询的联系人 ID;留空表示本会话的对方'),
373
+ query: string('想回忆的关键词;留空则只看长期事实'),
374
+ }, [], async (args, exec) => {
375
+ const store = runtime.memory;
376
+ assert(store, '长期记忆未启用');
377
+ await store.init();
378
+ const origin = runtime.access.originOf(exec.agent);
379
+ const target = args.peer_id ? toPeerId(args.peer_id) : (origin?.peerId ?? '');
380
+ assert(target, '无法确定要查询的联系人');
381
+ const recalled = store.recall(target, String(args.query ?? ''), {
382
+ limit: 10, factLimit: 10, minScore: 0,
383
+ });
384
+ return {
385
+ peer_id: target,
386
+ facts: recalled.facts.map((m) => ({ text: m.text, time: m.createdAt, key: m.factKey || undefined })),
387
+ events: recalled.events.map((e) => ({ text: e.memory.text, time: e.memory.createdAt, score: Number(e.score.toFixed(3)) })),
388
+ total: store.list(target).length,
389
+ };
390
+ });
391
+
392
+
393
+ tool('wx_memory_save', '主动把一件事记进长期记忆。用于对方明确让你记住,或出现了必须记住的约定。', {
394
+ text: string('要记住的内容,一句话'),
395
+ peer_id: string('记给哪个联系人;留空表示本会话的对方'),
396
+ kind: enumeration(['fact', 'event']),
397
+ fact_key: string('可选。会变的事用「对象.方面」,例如 对方.身高;不要写具体值'),
398
+ }, ['text'], async (args, exec) => {
399
+ const store = runtime.memory;
400
+ assert(store, '长期记忆未启用');
401
+ await store.init();
402
+ const origin = runtime.access.originOf(exec.agent);
403
+ const target = args.peer_id ? toPeerId(args.peer_id) : (origin?.peerId ?? '');
404
+ assert(target, '无法确定要记给谁');
405
+ // 非管理员只能记给本会话的对方,避免给任意人写记忆。
406
+ if (origin && !runtime.access.isOwner(origin)) {
407
+ assert(origin.peerId === target, '只能记住当前会话的对方');
408
+ }
409
+ const result = await store.remember(target, {
410
+ text: textArg(args.text, '记忆内容', 400),
411
+ kind: args.kind === 'fact' ? 'fact' : 'event',
412
+ importance: args.kind === 'fact' ? 2 : 1,
413
+ factKey: String(args.fact_key ?? '').slice(0, 40),
414
+ source: 'tool',
415
+ });
416
+ return { saved: Boolean(result), id: result?.entry?.id ?? '', superseded: result?.superseded ?? null };
417
+ });
418
+
419
+
420
+ tool('wx_meme_search', '在表情包图库里按关键词或情绪搜索。返回 id、描述和匹配分数,用 wx_meme_send 发送。', {
421
+ query: string('想表达的内容或情绪,例如「开心」「无语」'),
422
+ limit: { type: 'integer', description: '返回条数,默认 5' },
423
+ }, ['query'], async (args, exec) => runtime.runTool(async () => {
424
+ const lib = runtime.memes;
425
+ if (!lib) throw new Error('表情包图库未启用');
426
+ const hits = lib.search(String(args.query ?? ''), { limit: Math.min(20, Math.max(1, Number(args.limit) || 5)) });
427
+ return {
428
+ total: lib.stats().total,
429
+ hits: hits.map(({ entry, score }) => ({
430
+ id: entry.id, score: Number(score.toFixed(3)),
431
+ description: entry.description || '',
432
+ tags: entry.tags ?? [], emotions: entry.emotions ?? [],
433
+ })),
434
+ note: hits.length ? '用 wx_meme_send 发送选中的 id' : '没有匹配的表情,可以换个说法',
435
+ };
436
+ }, { allowOffline: false }));
437
+
438
+
439
+ tool('wx_meme_collect', '把一张图片收进表情包库。source 是本地路径或 http(s) 链接。默认进待审核池。', {
440
+ source: string('图片来源:本地绝对路径 / http(s) URL'),
441
+ approve: { type: 'boolean', description: 'true = 直接入库;默认 false 进待审核池' },
442
+ note: string('备注,通常写它表达的情绪'),
443
+ }, ['source'], async (args, exec) => runtime.runTool(async () => {
444
+ const lib = runtime.memes;
445
+ if (!lib) throw new Error('表情包图库未启用');
446
+ const bytes = await runtime.resolveImageBytes(String(args.source), exec.signal);
447
+ const result = await lib.addBuffer(bytes, {
448
+ source: 'tool',
449
+ note: String(args.note ?? ''),
450
+ requireApproval: args.approve !== true,
451
+ });
452
+ return result.ok
453
+ ? { status: result.pending ? 'pending' : 'stored', id: result.record.id, width: result.record.width, height: result.record.height }
454
+ : { status: 'skipped', reason: result.reason, duplicate: Boolean(result.duplicate) };
455
+ }, { allowOffline: true }));
456
+
457
+ // ---- interaction & group management ------------------------------------
458
+ // Ported from astrbot_plugin_wx_tools, minus the parts that do not fit: the
459
+ // browser and video analyser (this plugin just moved OFF a browser), the wake
460
+ // scheduler (it needs host-level timers), and send_group_notice (measured:
461
+ // 守护进程会对不支持的接口返回错误)。
462
+
463
+
464
+ tool('wx_web_search', '实时联网搜索。适合查新闻、文档、事实核验和近期变化。返回带 URL 的结果摘要。', {
465
+ query: string('搜索关键词'),
466
+ max_results: { type: 'integer', description: '返回条数,默认 5,最多 20' },
467
+ freshness: enumeration(['', 'day', 'week', 'month', 'year']),
468
+ }, ['query'], async (args, exec) => runtime.runTool(async () => {
469
+ const client = runtime.search;
470
+ if (!client) throw new Error('联网搜索未启用');
471
+ const text = await client.search(String(args.query ?? ''), {
472
+ maxResults: Number(args.max_results) || 5,
473
+ freshness: String(args.freshness ?? ''),
474
+ });
475
+ return { query: String(args.query), chars: text.length, result: { untrusted: true, text: text.slice(0, 6000) } };
476
+ }, { allowOffline: true }));
477
+
478
+
479
+ tool('wx_web_extract', '提取一个公网网页的可读正文(Markdown)。只接受公开 http/https,拒绝本机与内网地址。', {
480
+ url: string('要提取的网页地址'),
481
+ }, ['url'], async (args, exec) => runtime.runTool(async () => {
482
+ const client = runtime.search;
483
+ if (!client) throw new Error('联网搜索未启用');
484
+ const text = await client.extract(String(args.url ?? ''));
485
+ return { url: String(args.url), chars: text.length, result: { untrusted: true, text: text.slice(0, 8000) } };
486
+ }, { allowOffline: true }));
487
+
488
+
489
+ tool('wx_web_batch', '并行执行 1–5 个独立搜索,适合对比资料或快速收集多条线索。', {
490
+ queries: { type: 'array', items: { type: 'string' }, description: '1–5 个搜索关键词' },
491
+ }, ['queries'], async (args, exec) => runtime.runTool(async () => {
492
+ const client = runtime.search;
493
+ if (!client) throw new Error('联网搜索未启用');
494
+ const list = Array.isArray(args.queries) ? args.queries : [];
495
+ const text = await client.batchSearch(list);
496
+ return { count: list.length, chars: text.length, result: text.slice(0, 10_000) };
497
+ }, { allowOffline: true }));
498
+
499
+ // ---- virtual life --------------------------------------------------------
500
+ // Two tools: read the schedule, and regenerate the week. Everything else
501
+ // (outfit, meals, proactive switches) belongs in the panel, where a person can
502
+ // see what the model actually produced.
503
+
504
+
505
+ tool('wx_steam_status', '查看某个联系人绑定的 Steam 账号此刻在玩什么、在线状态、最近的游戏时长。不传 peer_id 时查当前对话对象。', {
506
+ peer_id: string('要查询的联系人 ID,留空则查当前对话对象'),
507
+ refresh: { type: 'boolean', description: '忽略缓存,强制重新查询' },
508
+ }, [], async (args, exec) => runtime.runTool(async () => {
509
+ const steam = runtime.steam;
510
+ if (!steam?.enabled) throw new Error('Steam 未启用:请先在面板「Steam」里填 API Key 并打开开关');
511
+ // 当前对话对象:私聊是对方,群聊是发言人(绑定要绑到人,不绑到群)。
512
+ const origin = access.context(exec?.agent);
513
+ const selfPeer = origin ? (origin.senderId || (origin.kind === 'private' ? origin.peerId : '')) : '';
514
+ const target = args.peer_id ? toPeerId(args.peer_id, '联系人 ID') : selfPeer;
515
+ if (!target) throw new Error('没有指定联系人 ID,也拿不到当前对话对象');
516
+ const status = await runtime.steamStatusFor(target, { force: args.refresh === true });
517
+ if (!status) return { bound: false, note: '这个联系人还没有绑定 Steam,或者 Steam 查询失败。绑定只能在面板「Steam」卡片里做,聊天里不能绑。' };
518
+ const { describeSteamStatus, formatPlaytime } = await import('./steam.mjs');
519
+ return {
520
+ bound: true,
521
+ steamId: status.steamId,
522
+ nickname: status.nickname,
523
+ state: status.state,
524
+ inGame: status.inGame || null,
525
+ summary: describeSteamStatus(status),
526
+ recentGames: (status.recentGames ?? []).map((g) => ({
527
+ name: g.name,
528
+ total: formatPlaytime(g.minutes) || null,
529
+ twoWeeks: formatPlaytime(g.minutes2Weeks) || null,
530
+ })),
531
+ gamesUnavailable: status.gamesUnavailable === true
532
+ ? '拿不到游戏时长:Steam 的「游戏详情」需要设为公开'
533
+ : undefined,
534
+ };
535
+ })),
536
+
537
+
538
+ tool('wx_life_status', '查看当前虚拟生活状态:今天在做什么、穿什么、吃什么,以及这一周的整体安排。', {
539
+ detail: enumeration(['today', 'week']),
540
+ }, [], async (args, exec) => runtime.runTool(async () => {
541
+ const life = runtime.life;
542
+ if (!life) throw new Error('虚拟人生未启用');
543
+ await life.init();
544
+ if (!life.ready) return { ready: false, note: '还没有生成日程,请先在面板里点「生成」' };
545
+ const now = new Date();
546
+ const plan = life.planFor(now);
547
+ const draw = life.drawFor(now);
548
+ const base = {
549
+ ready: true, weekday: plan.weekday, theme: plan.theme, mood: plan.mood,
550
+ longTerm: life.state.longTerm,
551
+ now: life.describe(now),
552
+ outfit: draw.outfit ? { style: draw.outfit.style, pieces: draw.outfit.pieces.map((p) => p.name) } : null,
553
+ // 晚上可能换了另一套,昼夜天气不同时才会出现。
554
+ eveningOutfit: draw.eveningOutfit && draw.outfit && draw.eveningOutfit.id !== draw.outfit.id
555
+ ? { style: draw.eveningOutfit.style, pieces: draw.eveningOutfit.pieces.map((p) => p.name) }
556
+ : null,
557
+ meals: draw.meals.map((m) => ({ slot: m.slot, place: m.place, dishes: m.dishes })),
558
+ };
559
+ if (args.detail === 'week') {
560
+ base.week = Object.entries(life.state.week).map(([index, day]) => ({
561
+ weekday: ['周一','周二','周三','周四','周五','周六','周日'][Number(index)],
562
+ theme: day.theme, mood: day.mood,
563
+ timeline: day.timeline.map((item) => ({
564
+ span: hhmmOf(item.start) + '-' + (item.end >= 1440 ? '24:00' : hhmmOf(item.end)),
565
+ activity: item.activity, location: item.location, state: item.state,
566
+ })),
567
+ }));
568
+ }
569
+ return base;
570
+ }, { allowOffline: true }));
571
+
572
+
573
+ tool('wx_life_generate', '重新生成虚拟人生:一整周的日程、穿搭池和三餐池。会调用一次模型,耗时较长。', {
574
+ force: { type: 'boolean', description: '已有数据时是否强制重新生成' },
575
+ }, [], async (args, exec) => runtime.runTool(async () => {
576
+ const generator = runtime.lifeGenerator;
577
+ if (!generator) throw new Error('虚拟人生未启用');
578
+ const result = await generator.generate({ force: args.force === true });
579
+ return result;
580
+ }, { allowOffline: true }));
581
+
582
+ return definitions;
583
+ }