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/lock.mjs ADDED
@@ -0,0 +1,204 @@
1
+ import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { hostname } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ export const LOCK_VERSION = 2;
7
+ export const DEFAULT_HEARTBEAT_MS = 15_000;
8
+ export const DEFAULT_STALE_MS = 90_000;
9
+
10
+ export class LockHeldError extends Error {
11
+ constructor(message, { path, owner = null, ageMs = null, reason = 'held' } = {}) {
12
+ super(message);
13
+ this.name = 'LockHeldError';
14
+ this.code = 'LOCK_HELD';
15
+ this.path = path;
16
+ this.owner = owner;
17
+ this.ageMs = ageMs;
18
+ this.reason = reason;
19
+ this.retryable = true;
20
+ }
21
+ }
22
+
23
+ export function lockOwnerAlive(pid) {
24
+ if (!Number.isInteger(pid) || pid <= 0) return false;
25
+ try {
26
+ process.kill(pid, 0);
27
+ return true;
28
+ } catch (error) {
29
+ // Windows can report EPERM for a process owned by another user. A live
30
+ // process is safer than stealing a lock that belongs to somebody else.
31
+ return error?.code === 'EPERM';
32
+ }
33
+ }
34
+
35
+ function ownerTimestamp(owner, mtimeMs) {
36
+ // updatedAt 才是心跳时间。文件 mtime 只作为旧格式的兜底,否则一次手工写入
37
+ // 或复制锁文件就会把「心跳过期」误判成「刚刚更新」。
38
+ const updated = Date.parse(String(owner?.updatedAt ?? ''));
39
+ if (Number.isFinite(updated)) return updated;
40
+ const created = Date.parse(String(owner?.createdAt ?? ''));
41
+ if (Number.isFinite(created)) return created;
42
+ return Number.isFinite(Number(mtimeMs)) ? Number(mtimeMs) : 0;
43
+ }
44
+
45
+ async function readLock(path) {
46
+ try {
47
+ const [text, info] = await Promise.all([readFile(path, 'utf8'), stat(path)]);
48
+ let owner = null;
49
+ try { owner = JSON.parse(text); } catch { /* malformed: treat as stale */ }
50
+ return { owner, mtimeMs: info.mtimeMs };
51
+ } catch (error) {
52
+ if (error?.code === 'ENOENT') return null;
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ export function lockOwnerFresh(owner, {
58
+ ageMs,
59
+ staleMs = DEFAULT_STALE_MS,
60
+ isProcessAlive = lockOwnerAlive,
61
+ } = {}) {
62
+ const pid = Number(owner?.pid);
63
+ if (!Number.isInteger(pid) || pid <= 0) return false;
64
+ if (!Number.isFinite(Number(ageMs)) || Number(ageMs) > staleMs) return false;
65
+ return isProcessAlive(pid);
66
+ }
67
+
68
+ function makeLockHandle(path, owner, options) {
69
+ const heartbeatMs = Math.max(1000, Number(options.heartbeatMs) || DEFAULT_HEARTBEAT_MS);
70
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
71
+ let released = false;
72
+ let compromised = false;
73
+ let heartbeatBusy = false;
74
+
75
+ const markCompromised = (error) => {
76
+ if (compromised || released) return;
77
+ compromised = true;
78
+ clearInterval(timer);
79
+ try { options.onCompromised?.(error); } catch { /* diagnostics only */ }
80
+ };
81
+
82
+ const heartbeat = async () => {
83
+ if (released || compromised || heartbeatBusy) return false;
84
+ heartbeatBusy = true;
85
+ try {
86
+ const current = await readLock(path);
87
+ if (!current || current.owner?.token !== owner.token) {
88
+ markCompromised(new Error('数据目录锁已被其他进程接管'));
89
+ return false;
90
+ }
91
+ owner.updatedAt = new Date(now()).toISOString();
92
+ // Write to a private temp file, re-check the token, then atomically
93
+ // replace. This keeps a heartbeat from leaving a half-written JSON file.
94
+ const temp = path + '.' + owner.token + '.heartbeat';
95
+ await writeFile(temp, JSON.stringify(owner), { mode: 0o600 });
96
+ const again = await readLock(path);
97
+ if (!again || again.owner?.token !== owner.token) {
98
+ await rm(temp, { force: true }).catch(() => {});
99
+ markCompromised(new Error('数据目录锁已被其他进程接管'));
100
+ return false;
101
+ }
102
+ await rename(temp, path);
103
+ return true;
104
+ } finally {
105
+ heartbeatBusy = false;
106
+ }
107
+ };
108
+
109
+ const timer = setInterval(() => {
110
+ heartbeat().catch(error => {
111
+ // A transient disk error must not make two runtimes believe they both own
112
+ // the directory. The next heartbeat checks the token again.
113
+ options.onHeartbeatError?.(error);
114
+ });
115
+ }, heartbeatMs);
116
+ timer.unref?.();
117
+
118
+ const release = async () => {
119
+ if (released) return;
120
+ released = true;
121
+ clearInterval(timer);
122
+ try {
123
+ const current = await readLock(path);
124
+ if (current?.owner?.token === owner.token) await rm(path, { force: true });
125
+ } catch (error) {
126
+ if (error?.code !== 'ENOENT') throw error;
127
+ }
128
+ };
129
+ release.owner = owner;
130
+ release.heartbeat = heartbeat;
131
+ release.isCompromised = () => compromised;
132
+ return release;
133
+ }
134
+
135
+ export async function acquireLock(dataDir, {
136
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
137
+ staleMs = DEFAULT_STALE_MS,
138
+ retries = 3,
139
+ now = () => Date.now(),
140
+ isProcessAlive = lockOwnerAlive,
141
+ onCompromised,
142
+ onHeartbeatError,
143
+ } = {}) {
144
+ await mkdir(dataDir, { recursive: true, mode: 0o700 });
145
+ const path = join(dataDir, 'runtime.lock');
146
+
147
+ for (let attempt = 0; attempt <= Math.max(0, Number(retries) || 0); attempt++) {
148
+ let file;
149
+ try {
150
+ file = await open(path, 'wx', 0o600);
151
+ } catch (error) {
152
+ if (error?.code !== 'EEXIST') throw error;
153
+ const current = await readLock(path);
154
+ if (!current) continue;
155
+
156
+ const ageMs = Math.max(0, now() - ownerTimestamp(current.owner, current.mtimeMs));
157
+ if (lockOwnerFresh(current.owner, { ageMs, staleMs, isProcessAlive })) {
158
+ const owner = current.owner;
159
+ throw new LockHeldError(
160
+ `数据目录已被使用:进程 ${owner.pid} 仍持有锁 ${path}。`,
161
+ { path, owner, ageMs, reason: 'fresh' },
162
+ );
163
+ }
164
+
165
+ // Move the stale file aside before creating a new one. Two contenders can
166
+ // race here; the loser gets EEXIST and retries.
167
+ const stalePath = `${path}.stale-${randomUUID()}`;
168
+ try {
169
+ await rename(path, stalePath);
170
+ } catch (renameError) {
171
+ if (renameError?.code === 'ENOENT') continue;
172
+ throw renameError;
173
+ }
174
+ await rm(stalePath, { force: true }).catch(() => {});
175
+ continue;
176
+ }
177
+
178
+ const createdAt = new Date(now()).toISOString();
179
+ const owner = {
180
+ version: LOCK_VERSION,
181
+ pid: process.pid,
182
+ token: randomUUID(),
183
+ hostname: hostname(),
184
+ execPath: process.execPath,
185
+ argv: process.argv.slice(0, 3),
186
+ createdAt,
187
+ updatedAt: createdAt,
188
+ };
189
+ try {
190
+ await file.writeFile(JSON.stringify(owner));
191
+ await file.close();
192
+ } catch (error) {
193
+ try { await file.close(); } catch { /* already closed */ }
194
+ await rm(path, { force: true }).catch(() => {});
195
+ throw error;
196
+ }
197
+ return makeLockHandle(path, owner, { heartbeatMs, now, onCompromised, onHeartbeatError });
198
+ }
199
+
200
+ throw new LockHeldError(
201
+ `无法获取数据目录锁:${path}。其他实例可能正在启动。`,
202
+ { path, reason: 'contended' },
203
+ );
204
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Vision classification for the sticker library.
3
+ *
4
+ * The upstream Python projects run a dedicated VLM over every image. This does the
5
+ * same with the Host's own agent runtime: one throwaway agent per batch, given the
6
+ * images as attachment parts and asked for structured labels back.
7
+ *
8
+ * Two things make it affordable. Images are classified in SMALL BATCHES so one
9
+ * agent turn covers several stickers, and the result is written to the index so a
10
+ * sticker is never classified twice. \`visionClassify\` turns it off entirely.
11
+ */
12
+ import { assert, hostSelection, stripHostPrompt } from './util.mjs';
13
+ import { sessionEventList } from './runtime.mjs';
14
+
15
+ /** The prompt is deliberately narrow: labels are for retrieval, not for prose. */
16
+ const CLASSIFY_PROMPT = `你在给一个表情包图库打标签,标签会用于以后按语境检索。
17
+
18
+ 对每张图输出一个对象,不要解释、不要客套,只输出 JSON 数组:
19
+ [{"index":0,"description":"一句话说清这张图表达什么","tags":["关键词"],"emotions":["情绪"]}]
20
+
21
+ 规则:
22
+ - description 写这张图在聊天里用来表达什么,不超过 30 字,不要以「这张图」开头。
23
+ - tags 是检索词:画面内容、文字、常见使用场景,2–5 个。
24
+ - emotions 是情绪,从这些里选 1–3 个:开心 无语 生气 难过 害羞 惊讶 得意 敷衍 安慰 撒娇 疑惑 尴尬
25
+ - 图上的文字要原样收进 tags。
26
+ - 只输出 JSON,不要 markdown 代码块。`;
27
+
28
+ /**
29
+ * Pull a JSON array out of whatever the model actually returned.
30
+ *
31
+ * Models wrap JSON in prose or fences often enough that a bare JSON.parse fails on
32
+ * otherwise usable answers; this recovers the array instead of losing the batch.
33
+ */
34
+ export function extractJsonArray(text) {
35
+ const source = String(text ?? '');
36
+ const fenced = source.match(/```(?:json)?\s*([\s\S]*?)```/i);
37
+ const body = fenced ? fenced[1] : source;
38
+ const start = body.indexOf('[');
39
+ const end = body.lastIndexOf(']');
40
+ if (start < 0 || end <= start) return null;
41
+ try {
42
+ const parsed = JSON.parse(body.slice(start, end + 1));
43
+ return Array.isArray(parsed) ? parsed : null;
44
+ } catch { return null; }
45
+ }
46
+
47
+ /** Normalise one model-produced label object into the shape the library stores. */
48
+ export function normalizeLabels(raw) {
49
+ if (!raw || typeof raw !== 'object') return null;
50
+ const clean = (value, limit) => {
51
+ const list = Array.isArray(value) ? value : (typeof value === 'string' ? value.split(/[,,、\s]+/) : []);
52
+ return [...new Set(list.map((x) => String(x ?? '').trim()).filter(Boolean))].slice(0, limit);
53
+ };
54
+ const description = String(raw.description ?? '').trim().slice(0, 300);
55
+ const tags = clean(raw.tags, 8);
56
+ const emotions = clean(raw.emotions, 4);
57
+ if (!description && tags.length === 0 && emotions.length === 0) return null;
58
+ return { description, tags, emotions };
59
+ }
60
+
61
+ export class MemeClassifier {
62
+ constructor(runtime, { batchSize = 4, logger = console } = {}) {
63
+ this.runtime = runtime;
64
+ this.batchSize = batchSize;
65
+ this.logger = logger;
66
+ this.running = false;
67
+ }
68
+
69
+ /** Whether the Host can hand an image to a model at all. */
70
+ canClassify() {
71
+ const attachments = this.runtime.ctx?.get?.('attachments');
72
+ return Boolean(attachments && typeof attachments.saveImage === 'function' && this.runtime.ctx?.agents?.create);
73
+ }
74
+
75
+ /**
76
+ * Classify up to \`max\` unclassified stickers.
77
+ *
78
+ * Returns a tally rather than throwing: a failed batch leaves its stickers
79
+ * unclassified, which means the next run simply retries them.
80
+ */
81
+ async runOnce({ max = 8 } = {}) {
82
+ if (this.running) return { ok: false, reason: '已有分类任务在跑' };
83
+ if (!this.canClassify()) return { ok: false, reason: 'Host 不支持把图片交给模型' };
84
+ const library = this.runtime.memes;
85
+ if (!library) return { ok: false, reason: '表情包图库未启用' };
86
+ await library.init();
87
+
88
+ const targets = library.unclassified(max);
89
+ if (!targets.length) return { ok: true, classified: 0, remaining: 0, note: '没有待分类的表情包' };
90
+
91
+ this.running = true;
92
+ let classified = 0;
93
+ const failures = [];
94
+ try {
95
+ const attachments = this.runtime.ctx.get('attachments');
96
+ for (let offset = 0; offset < targets.length; offset += this.batchSize) {
97
+ const batch = targets.slice(offset, offset + this.batchSize);
98
+ try {
99
+ const parts = [{ type: 'text', text: CLASSIFY_PROMPT + `\n\n本批共 ${batch.length} 张图,index 从 0 开始。` }];
100
+ for (const [index, entry] of batch.entries()) {
101
+ const bytes = await library.bytesOf(entry);
102
+ const ref = await attachments.saveImage({
103
+ data: new Uint8Array(bytes),
104
+ mediaType: entry.mediaType,
105
+ name: 'meme-' + entry.id,
106
+ });
107
+ parts.push({ type: 'text', text: `第 ${index} 张:` });
108
+ parts.push({ type: 'image', attachment: ref });
109
+ }
110
+ const reply = await this.#ask(parts);
111
+ const labels = extractJsonArray(reply);
112
+ if (!labels) { failures.push({ batch: offset, reason: '模型未返回可解析的 JSON' }); continue; }
113
+ for (const item of labels) {
114
+ const index = Number(item?.index);
115
+ if (!Number.isInteger(index) || index < 0 || index >= batch.length) continue;
116
+ const normalized = normalizeLabels(item);
117
+ if (!normalized) continue;
118
+ await library.annotate(batch[index].id, normalized);
119
+ classified++;
120
+ }
121
+ } catch (error) {
122
+ failures.push({ batch: offset, reason: String(error?.message ?? error).slice(0, 200) });
123
+ }
124
+ }
125
+ } finally {
126
+ this.running = false;
127
+ }
128
+ return {
129
+ ok: true,
130
+ classified,
131
+ remaining: library.unclassified(1).length ? library.stats().unclassified : 0,
132
+ failures,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * One throwaway agent turn that returns the model's raw text.
138
+ *
139
+ * The agent is disposed immediately: classification has no conversation state,
140
+ * and keeping one alive per batch would leak sessions for a job that runs once.
141
+ */
142
+ async #ask(content) {
143
+ const runtime = this.runtime;
144
+ const defaultSelection = runtime.ctx.get?.('agentDefaultModel')?.currentSelection?.();
145
+ const route = Object.keys(runtime.config.route ?? {}).length ? runtime.config.route : undefined;
146
+ const agentOptions = route ?? hostSelection(defaultSelection);
147
+ const id = `qq-meme-classify-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
148
+ const handle = await runtime.ctx.agents.create({
149
+ sessionId: id,
150
+ meta: { cwd: runtime.config.dataDir },
151
+ ...(agentOptions ? { agentOptions } : {}),
152
+ setup: async (agentCtx) => {
153
+ stripHostPrompt(agentCtx);
154
+ // No tools: this turn must answer, not act.
155
+ if (typeof agentCtx.tools?.restrict === 'function') agentCtx.tools.restrict({ allow: [] });
156
+ agentCtx.systemPrompt.section({
157
+ name: 'meme-classifier', order: 500,
158
+ text: '你是一个图像标注器。只输出调用方要求的 JSON,不写解释。',
159
+ });
160
+ },
161
+ });
162
+ try {
163
+ assert(handle?.agent && typeof handle.agent.whenIdle === 'function', 'Host Agent API 不兼容');
164
+ const before = Number.isInteger(handle.agent.session?.seq) ? handle.agent.session.seq : 0;
165
+ handle.agent.followup(runtime.createUserMessage({ content, source: { kind: 'user' } }));
166
+ // A1 补漏:与 runtime 的 #waitAgentIdle 同款硬超时,防止宿主 whenIdle 挂住。
167
+ // 分类是 fire-and-forget,挂住不阻塞消息,但会泄漏一个 agent 会话。
168
+ const idleMs = 60_000;
169
+ const idleOk = await Promise.race([
170
+ Promise.resolve().then(() => handle.agent.whenIdle()).then(() => true).catch(() => true),
171
+ new Promise((resolve) => { const t = setTimeout(() => resolve(false), idleMs); t.unref?.(); }),
172
+ ]);
173
+ if (!idleOk) {
174
+ try { handle.agent.cancel({ kind: 'user' }); } catch {}
175
+ throw new Error('表情分类回合超时(' + idleMs + 'ms)');
176
+ }
177
+ const events = sessionEventList(handle.agent.session).slice(before);
178
+ const texts = [];
179
+ for (const event of events) {
180
+ if (event.type !== 'assistant/message') continue;
181
+ for (const part of event.data?.message?.content ?? []) {
182
+ if (part?.type === 'text' && part.text) texts.push(part.text);
183
+ }
184
+ }
185
+ return texts.join('\n');
186
+ } finally {
187
+ try { await handle?.dispose?.(); } catch { /* the turn is already over */ }
188
+ }
189
+ }
190
+ }