pygmalion 0.1.8 → 0.1.10

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.
@@ -0,0 +1,294 @@
1
+ /**
2
+ * MonsterParty(怪兽派对X / 雷电)驱动 —— 移植自 toy-protocol/ 已验证协议。
3
+ *
4
+ * 拓扑:分享链接 token → 解析会话 → 连 WS 成为 receiver → 下发行程/强度命令,
5
+ * 云端中继转发给用户手机 Hub(BLE)→ 玩具。
6
+ *
7
+ * 协议要点(实测):
8
+ * join f2 = { f1=uuid, f2=nickname, f3="", f4="", f7=1, f8=uuid, f10="remote-web", f11="1.0.0" }
9
+ * 心跳 f13 = ""(每 ~1s)
10
+ * 强度 f4 = { f1=tick, f2=[0-100] }(持续刷新以"保持运行")
11
+ * 行程 f14 = { f1=tick, f2=0, f3={ "segment", idx=A, "A,B" } }(变更时发一次)
12
+ * 服务端推送 f3=会话(加入成功)、f1=错误(如 duplicate receiver)。tick 每连接从回包学习。
13
+ */
14
+ import { randomUUID } from 'node:crypto';
15
+ import WebSocket from 'ws';
16
+ import { encodeFields, decodeFields } from './pb.mjs';
17
+
18
+ const API_BASE = 'https://api.monsterparty.cc';
19
+ const NICKNAME = 'pygmalion';
20
+ const VERSION = '1.0.0';
21
+ const SLIDER_INTERVAL_MS = 50; // 持续刷新强度(页面实测 ~20Hz)
22
+ const KEEPALIVE_INTERVAL_MS = 1000;
23
+ const JOIN_TIMEOUT_MS = 20000;
24
+
25
+ /** 雷电(套弄)能力:强度 0-100 + 行程区间边界 0/33/66/100(L1 0~33 最深 / L2 33~66 / L3 66~100 拔出)。 */
26
+ export const MONSTERPARTY_CAPABILITY = {
27
+ kind: 'monsterparty',
28
+ label: 'MonsterParty 雷电',
29
+ intensity: { min: 0, max: 100 },
30
+ stroke: {
31
+ bounds: [0, 33, 66, 100],
32
+ zones: { L1: [0, 33], L2: [33, 66], L3: [66, 100] },
33
+ note: '行程=区间边界 A,B(0/33/66/100),如 "0,66";"0,0"=停',
34
+ },
35
+ noAutoStop: true, // 无自动停止,由 dsh 决定何时停(用户可要求 AI 停/手动停)
36
+ };
37
+
38
+ const DOMAIN_RE = /(?:monsterparty\.cc|monsterhub\.cn|monsterpub\.com)/i;
39
+
40
+ /**
41
+ * 从文本中找 MonsterParty 分享链接并提取 token。
42
+ * @returns { { token: string, raw: string, kind: 'monsterparty' } | null }
43
+ */
44
+ export function parseLink(text) {
45
+ const s = String(text ?? '');
46
+ // 抓 monsterparty 域 URL(www./m. 可选);token 取 query 或 fragment 里的 token= 参数。
47
+ const urlRe = new RegExp(
48
+ `https?:\\/\\/(?:www\\.|m\\.)?${DOMAIN_RE.source}\\/[^\\s"'<>,。]*`,
49
+ 'gi',
50
+ );
51
+ const found = urlRe.exec(s);
52
+ if (!found) return null;
53
+ const raw = found[0];
54
+ const tokenMatch = /[?#&]token=([A-Za-z0-9_\-]+)/.exec(raw);
55
+ if (!tokenMatch) return null;
56
+ return { token: tokenMatch[1], raw, kind: 'monsterparty' };
57
+ }
58
+
59
+ /** 解析会话(验证链接有效)。@returns { ok:true, session } | { ok:false, error } */
60
+ export async function resolveSession(token) {
61
+ const url = `${API_BASE}/play/v3/remote/session?token=${encodeURIComponent(token)}`;
62
+ let res;
63
+ try {
64
+ const ctl = AbortSignal.timeout(15000);
65
+ res = await fetch(url, { cache: 'no-store', signal: ctl });
66
+ } catch (e) {
67
+ return { ok: false, error: `解析会话网络失败: ${e instanceof Error ? e.message : String(e)}` };
68
+ }
69
+ let j;
70
+ try { j = await res.json(); } catch { return { ok: false, error: `解析会话响应异常(HTTP ${res.status})` }; }
71
+ if (!j || j.message !== 'ok' || !j.data) {
72
+ const msg = j?.message ?? `HTTP ${res.status}`;
73
+ return { ok: false, error: `链接无效或已过期(${msg})` };
74
+ }
75
+ return { ok: true, session: j.data };
76
+ }
77
+
78
+ /** 帧构造(encodeFields 纯函数,tick 由连接实例持有)。 */
79
+ function fJoin(uuid) {
80
+ return encodeFields([{
81
+ num: 2, wire: 2,
82
+ value: encodeFields([
83
+ { num: 1, wire: 2, value: uuid },
84
+ { num: 2, wire: 2, value: NICKNAME },
85
+ { num: 3, wire: 2, value: '' },
86
+ { num: 4, wire: 2, value: '' },
87
+ { num: 7, wire: 0, value: 1 },
88
+ { num: 8, wire: 2, value: uuid },
89
+ { num: 10, wire: 2, value: 'remote-web' },
90
+ { num: 11, wire: 2, value: VERSION },
91
+ ]),
92
+ }]);
93
+ }
94
+ const fHeartbeat = () => encodeFields([{ num: 13, wire: 2, value: '' }]);
95
+ const fSlider = (tick, v) => encodeFields([{
96
+ num: 4, wire: 2,
97
+ value: encodeFields([
98
+ { num: 1, wire: 0, value: tick },
99
+ { num: 2, wire: 2, value: Buffer.from([Number(v) & 0xff]) },
100
+ ]),
101
+ }]);
102
+ const fSegment = (tick, a, b, idx = a) => encodeFields([{
103
+ num: 14, wire: 2,
104
+ value: encodeFields([
105
+ { num: 1, wire: 0, value: tick },
106
+ { num: 2, wire: 0, value: 0 },
107
+ { num: 3, wire: 2, value: encodeFields([
108
+ { num: 1, wire: 2, value: 'segment' },
109
+ { num: 2, wire: 0, value: idx },
110
+ { num: 3, wire: 2, value: `${a},${b}` },
111
+ ]) },
112
+ ]),
113
+ }]);
114
+
115
+ function walkVarints(fields, acc) {
116
+ for (const f of fields) {
117
+ if (f.error) continue;
118
+ if (f.wire === 0 && f.varint !== undefined) acc.push(f.varint);
119
+ if (f.nested) walkVarints(f.nested, acc);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 单连接控制。tick 每连接独立,从服务端回包学习;错误(如 duplicate receiver)经
125
+ * opts.onError 回调并断开。
126
+ */
127
+ export class MonsterPartyConn {
128
+ /**
129
+ * @param {object} session resolveSession 返回的 data(含 session_id / ws_endpoint)
130
+ * @param {object} [opts] { nickname?, log? }
131
+ */
132
+ constructor(session, opts = {}) {
133
+ this.session = session;
134
+ this.log = opts.log;
135
+ this.tick = 963835321n; // 默认;收到服务端会话帧后动态更新
136
+ this.joined = false;
137
+ this.closed = false;
138
+ this._ws = null;
139
+ this._uuid = randomUUID();
140
+ this._keepAliveTimer = null;
141
+ this._sliderTimer = null;
142
+ this._intensity = 0;
143
+ this._stroke = null; // [a,b]
144
+ this._resolveJoined = null;
145
+ this._rejectJoined = null;
146
+ this._connectTimer = null;
147
+ }
148
+
149
+ /** 建立连接并加入。resolve 当收到会话帧(加入成功);reject 当错误/关闭/超时。 */
150
+ connect() {
151
+ return new Promise((resolve, reject) => {
152
+ if (this._ws) { reject(new Error('重复 connect')); return; }
153
+ this._resolveJoined = resolve;
154
+ this._rejectJoined = reject;
155
+ let ws;
156
+ try { ws = new WebSocket(this.session.ws_endpoint); }
157
+ catch (e) { reject(new Error(`WebSocket 创建失败: ${e.message}`)); return; }
158
+ this._ws = ws;
159
+ ws.on('open', () => this._onOpen());
160
+ ws.on('message', (data) => this._onMessage(Buffer.isBuffer(data) ? data : Buffer.from(data)));
161
+ ws.on('error', (e) => this._fail(new Error(`连接错误: ${e?.message ?? ''}`), false));
162
+ ws.on('close', (code, reason) => this._onClose(code, reason));
163
+ this._connectTimer = setTimeout(() => this._fail(new Error('加入超时(链接可能已失效)'), true), JOIN_TIMEOUT_MS);
164
+ });
165
+ }
166
+
167
+ _onOpen() {
168
+ if (this.log) this.log.debug?.('mp conn open, join %s', this.session.session_id);
169
+ this._send(fJoin(this._uuid));
170
+ this._keepAliveTimer = setInterval(() => { try { this._send(fHeartbeat()); } catch { /* ignore */ } }, KEEPALIVE_INTERVAL_MS);
171
+ this._keepAliveTimer.unref?.();
172
+ }
173
+
174
+ _onMessage(buf) {
175
+ let fields;
176
+ try { fields = decodeFields(buf); } catch { return; }
177
+ // 学习 tick:任意 1e8~2e9 的 varint 视为设备 tick
178
+ const vars = [];
179
+ walkVarints(fields, vars);
180
+ for (const v of vars) if (v >= 100_000_000n && v <= 2_000_000_000n) { this.tick = v; break; }
181
+ // 错误帧:f1 { f1=code, f2="session error: ..." } → 服务器拒绝
182
+ const top = fields[0];
183
+ if (top && top.num === 1 && top.nested) {
184
+ const msg = top.nested.find((f) => f.num === 2 && f.ascii && /error/i.test(f.ascii));
185
+ if (msg) { this._fail(new Error(msg.ascii), true); return; }
186
+ }
187
+ // f3 会话帧 = 加入成功
188
+ if (!this.joined && fields.some((f) => f.num === 3 && f.nested)) {
189
+ this.joined = true;
190
+ if (this._connectTimer) { clearTimeout(this._connectTimer); this._connectTimer = null; }
191
+ const resolve = this._resolveJoined;
192
+ this._resolveJoined = null;
193
+ resolve?.({ sessionId: this.session.session_id });
194
+ }
195
+ }
196
+
197
+ _onClose(code, reason) {
198
+ const wasClosed = this.closed;
199
+ this.closed = true;
200
+ this._stopTimers();
201
+ if (!this.joined && this._rejectJoined) {
202
+ const reject = this._rejectJoined;
203
+ this._rejectJoined = null;
204
+ reject(new Error(`连接关闭(${code}${reason ? `: ${reason}` : ''})`));
205
+ } else if (!wasClosed) {
206
+ // 已加入后的异常断开
207
+ if (this.log) this.log.warn?.('mp conn closed(%s) %s', code, reason ?? '');
208
+ }
209
+ }
210
+
211
+ _fail(err, hardClose) {
212
+ if (this.closed) return;
213
+ if (hardClose) { try { this._ws?.close(); } catch { /* ignore */ } }
214
+ if (!this.joined && this._rejectJoined) {
215
+ const reject = this._rejectJoined;
216
+ this._rejectJoined = null;
217
+ reject(err);
218
+ }
219
+ if (this.log) this.log.warn?.('mp conn fail: %s', err.message);
220
+ if (hardClose) { try { this._ws?.terminate?.(); } catch { /* ignore */ } }
221
+ }
222
+
223
+ _stopTimers() {
224
+ if (this._keepAliveTimer) { clearInterval(this._keepAliveTimer); this._keepAliveTimer = null; }
225
+ if (this._sliderTimer) { clearInterval(this._sliderTimer); this._sliderTimer = null; }
226
+ if (this._connectTimer) { clearTimeout(this._connectTimer); this._connectTimer = null; }
227
+ }
228
+
229
+ _send(buf) {
230
+ const ws = this._ws;
231
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
232
+ try { ws.send(buf); } catch { /* ignore */ }
233
+ }
234
+
235
+ /** 行程区间 [a,b](a/b∈0/33/66/100),变更时下发一次 segment。 */
236
+ sendStroke(a, b) {
237
+ const lo = Math.min(Number(a) || 0, Number(b) || 0);
238
+ const hi = Math.max(Number(a) || 0, Number(b) || 0);
239
+ this._stroke = [lo, hi];
240
+ this._send(fSegment(this.tick, lo, hi));
241
+ return { stroke: `${lo},${hi}` };
242
+ }
243
+
244
+ /**
245
+ * 强度 0-100。>0 时启动持续 slider 刷新循环(保持"当前强度运行"的载体);0 时停循环
246
+ * 并补一段归零帧。
247
+ */
248
+ setIntensity(v) {
249
+ const val = Math.max(0, Math.min(100, Math.round(Number(v) || 0)));
250
+ this._intensity = val;
251
+ if (val > 0) {
252
+ this._startSliderLoop();
253
+ } else {
254
+ this._stopSliderLoop();
255
+ this._burstZero();
256
+ }
257
+ return { intensity: val };
258
+ }
259
+
260
+ _startSliderLoop() {
261
+ if (this._sliderTimer) return;
262
+ this._sliderTimer = setInterval(() => {
263
+ if (this.closed) { this._stopSliderLoop(); return; }
264
+ this._send(fSlider(this.tick, this._intensity));
265
+ }, SLIDER_INTERVAL_MS);
266
+ this._sliderTimer.unref?.();
267
+ this._send(fSlider(this.tick, this._intensity)); // 立即来一帧
268
+ }
269
+
270
+ _stopSliderLoop() {
271
+ if (this._sliderTimer) { clearInterval(this._sliderTimer); this._sliderTimer = null; }
272
+ }
273
+
274
+ _burstZero() {
275
+ let n = 0;
276
+ const iv = setInterval(() => {
277
+ if (this.closed || ++n > 20) { clearInterval(iv); return; }
278
+ this._send(fSlider(this.tick, 0));
279
+ }, 50);
280
+ iv.unref?.();
281
+ }
282
+
283
+ /** 停止(强度归零)。 */
284
+ stop() { this.setIntensity(0); return { intensity: 0 }; }
285
+
286
+ /** 关闭连接并清理。 */
287
+ close() {
288
+ this.closed = true;
289
+ this._stopTimers();
290
+ try { this._ws?.close(); } catch { /* ignore */ }
291
+ try { this._ws?.terminate?.(); } catch { /* ignore */ }
292
+ this._ws = null;
293
+ }
294
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * MonsterParty WS protobuf 线格式编解码(移植自 toy-protocol/,协议已实测验证)。
3
+ * 仅依赖 node:buffer;encode 用于构造帧,decode 用于解析服务端回包。
4
+ */
5
+
6
+ /** 读 varint(用于解码)。返回 { value: bigint, next: 下一字节下标 }。 */
7
+ export function readVarint(buf, i) {
8
+ let result = 0n, shift = 0n;
9
+ while (i < buf.length) {
10
+ const b = buf[i++];
11
+ result |= BigInt(b & 0x7f) << shift;
12
+ if (!(b & 0x80)) return { value: result, next: i };
13
+ shift += 7n;
14
+ if (shift > 63n) throw new Error('varint too long');
15
+ }
16
+ throw new Error('truncated varint');
17
+ }
18
+
19
+ /** 写 varint(用于编码)。返回写入后的下标。 */
20
+ export function writeVarint(buf, offset, value) {
21
+ let n = BigInt(value), i = offset;
22
+ for (;;) {
23
+ const byte = Number(n & 0x7fn);
24
+ n >>= 7n;
25
+ if (n === 0n) { buf[i++] = byte; break; }
26
+ buf[i++] = byte | 0x80;
27
+ }
28
+ return i;
29
+ }
30
+
31
+ /**
32
+ * 把字段列表编码为一条 protobuf 消息。
33
+ * 字段格式 { num, wire, value }:wire 0=varint(value 数字)、2=bytes(value Buffer/字符串)、
34
+ * 5=fixed32、1=fixed64;value 可为嵌套 encodeFields 返回的 Buffer。
35
+ */
36
+ export function encodeFields(fields) {
37
+ const chunks = [];
38
+ for (const f of fields) {
39
+ const tag = Buffer.alloc(10);
40
+ chunks.push(tag.subarray(0, writeVarint(tag, 0, (BigInt(f.num) << 3n) | BigInt(f.wire))));
41
+ if (f.wire === 0) {
42
+ const b = Buffer.alloc(10);
43
+ chunks.push(b.subarray(0, writeVarint(b, 0, BigInt(f.value))));
44
+ } else if (f.wire === 2) {
45
+ const bytes = typeof f.value === 'string' ? Buffer.from(f.value, 'utf8') : Buffer.from(f.value);
46
+ const lb = Buffer.alloc(10);
47
+ chunks.push(lb.subarray(0, writeVarint(lb, 0, BigInt(bytes.length))), bytes);
48
+ } else if (f.wire === 5) {
49
+ const b = Buffer.alloc(4);
50
+ b.writeUInt32LE(Number(f.value) >>> 0);
51
+ chunks.push(b);
52
+ } else if (f.wire === 1) {
53
+ const b = Buffer.alloc(8);
54
+ b.writeBigUInt64LE(BigInt(f.value));
55
+ chunks.push(b);
56
+ } else {
57
+ throw new Error(`不支持的线类型 ${f.wire}`);
58
+ }
59
+ }
60
+ return Buffer.concat(chunks);
61
+ }
62
+
63
+ /**
64
+ * 解码一条 protobuf 消息。每字段含 num/wire;wire0 附 varint、wire2 附 ascii/hex 与
65
+ * 可能的 nested(递归解码)。供解析服务端帧(tick 学习 / 错误识别)用。
66
+ */
67
+ export function decodeFields(buf, depth = 0) {
68
+ const out = [];
69
+ let i = 0;
70
+ while (i < buf.length) {
71
+ try {
72
+ const { value: tag, next: n1 } = readVarint(buf, i);
73
+ const num = Number(tag >> 3n);
74
+ const wire = Number(tag & 7n);
75
+ if (num === 0) break; // 非法
76
+ let val;
77
+ switch (wire) {
78
+ case 0: { const v = readVarint(buf, n1); val = { varint: v.value, signed: BigInt.asIntN(64, v.value), next: v.next }; break; }
79
+ case 1: { val = { bytes: buf.subarray(n1, n1 + 8).toString('hex'), next: n1 + 8 }; break; }
80
+ case 2: {
81
+ const len = readVarint(buf, n1);
82
+ const L = Number(len.value);
83
+ const raw = buf.subarray(Number(len.next), Number(len.next) + L);
84
+ const next = Number(len.next) + L;
85
+ const ascii = [...raw].map((c) => (c >= 32 && c < 127) ? String.fromCharCode(c) : '.').join('');
86
+ const allPrintable = [...raw].every((c) => c >= 32 && c < 127);
87
+ let nested = null;
88
+ if (L >= 2 && !allPrintable) {
89
+ try {
90
+ const sub = decodeFields(raw, depth + 1);
91
+ const strict = sub.length >= 1 && sub.length <= 32
92
+ && sub.every((f) => !f.error && f.num >= 1 && (f.wire === 0 || f.wire === 1 || f.wire === 2 || f.wire === 5));
93
+ if (strict) nested = sub;
94
+ } catch { /* 非消息 */ }
95
+ }
96
+ val = { len: L, hex: raw.toString('hex'), ascii, nested, next };
97
+ break;
98
+ }
99
+ case 5: { val = { bytes: buf.subarray(n1, n1 + 4).toString('hex'), next: n1 + 4 }; break; }
100
+ default: val = { wire, next: n1 };
101
+ }
102
+ out.push({ num, wire, ...val });
103
+ i = val.next;
104
+ } catch (e) {
105
+ out.push({ error: e.message, at: i });
106
+ break;
107
+ }
108
+ }
109
+ return out;
110
+ }
package/src/http-api.js CHANGED
@@ -371,6 +371,41 @@ async function handleArchive(deps, res, body) {
371
371
  }
372
372
  }
373
373
 
374
+ /**
375
+ * `POST <prefix>/toycmd` — 设备 toy 脚本的参数下发端点(helper 的 toy.set/stop 经此到达
376
+ * DeviceManager)。鉴权同上 Bearer token;roleId 由该 bot 唯一决定。
377
+ */
378
+ async function handleToyCmd(deps, res, body) {
379
+ const devices = deps.devices;
380
+ if (!devices) {
381
+ sendJson(res, 503, { ok: false, error: '设备服务不可用' });
382
+ return;
383
+ }
384
+ const action = body?.action;
385
+ let result;
386
+ if (action === 'wake') {
387
+ // 脚本运行中请求发言:唤醒导演判断是否开口(可说可静默)
388
+ result = await devices.wakeFromScript({
389
+ roleId: deps.roleId,
390
+ mood: typeof body?.mood === 'string' ? body.mood : undefined,
391
+ topic: typeof body?.topic === 'string' ? body.topic : undefined,
392
+ reason: typeof body?.reason === 'string' ? body.reason : undefined,
393
+ });
394
+ if (!result?.ok && result?.skipped === 'coalesced') result = { ok: true, skipped: 'coalesced' };
395
+ } else if (action === 'stop') {
396
+ result = await devices.applyFromTool({ roleId: deps.roleId, stop: true, fromScript: true });
397
+ } else {
398
+ result = await devices.applyFromTool({
399
+ roleId: deps.roleId,
400
+ deviceId: typeof body?.deviceId === 'string' ? body.deviceId : undefined,
401
+ intensity: body?.intensity,
402
+ stroke: body?.stroke,
403
+ fromScript: true,
404
+ });
405
+ }
406
+ sendJson(res, 200, { ok: Boolean(result?.ok), ...result });
407
+ }
408
+
374
409
  /**
375
410
  * Build the prefix-route handler for the webServer registration.
376
411
  * @param deps - mount facts plus the pipelines the endpoints drive.
@@ -400,6 +435,7 @@ export function createHttpApiHandler(deps) {
400
435
  wakeup: `POST ${deps.mountPath}/wakeup`,
401
436
  archive: `POST ${deps.mountPath}/archive`,
402
437
  channels: `GET ${deps.mountPath}/channels`,
438
+ toycmd: `POST ${deps.mountPath}/toycmd`,
403
439
  },
404
440
  });
405
441
  return;
@@ -431,6 +467,15 @@ export function createHttpApiHandler(deps) {
431
467
  await handleArchive(deps, res, body);
432
468
  return;
433
469
  }
470
+ if (suffix === '/toycmd') {
471
+ if (req.method !== 'POST') {
472
+ sendJson(res, 405, { ok: false, error: 'toycmd 只接受 POST' });
473
+ return;
474
+ }
475
+ const body = await readJsonBody(req);
476
+ await handleToyCmd(deps, res, body);
477
+ return;
478
+ }
434
479
  if (suffix === '/channels') {
435
480
  if (req.method !== 'GET') {
436
481
  sendJson(res, 405, { ok: false, error: 'channels 只接受 GET' });
package/src/inbound.js CHANGED
@@ -99,6 +99,7 @@ export function normalizeMessage(payload, eventType) {
99
99
  msgElements: elements.map((el) => ({
100
100
  msg_idx: typeof el.msg_idx === 'string' ? el.msg_idx : undefined,
101
101
  content: typeof el.content === 'string' ? el.content : undefined,
102
+ url: typeof el.url === 'string' ? el.url : undefined,
102
103
  attachments: [],
103
104
  })),
104
105
  mentions,
@@ -120,6 +121,7 @@ export function normalizeMessage(payload, eventType) {
120
121
  msgElements: elements.map((el) => ({
121
122
  msg_idx: typeof el.msg_idx === 'string' ? el.msg_idx : undefined,
122
123
  content: typeof el.content === 'string' ? el.content : undefined,
124
+ url: typeof el.url === 'string' ? el.url : undefined,
123
125
  attachments: [],
124
126
  })),
125
127
  mentions,
@@ -524,7 +526,31 @@ export class InboundPipeline {
524
526
  extras.unshift('[身份提醒] 你是导演,不是角色本人;以角色说话只走 director_send。');
525
527
  } catch (e) { this.deps.log.warn('identity hint failed: %o', e); }
526
528
  }
527
- const text = assembleText(cleaned, quote, extras);
529
+ // 设备分享链接激活(仅 c2c 拥有者会话):识别 MonsterParty 链接 → 解析 → 激活该角色设备;
530
+ // 成功则把 token 从模型文本剥掉(单次敏感凭证,不喂模型/不进记忆)。
531
+ let consumedLinkRaw = null;
532
+ if (message.kind === 'c2c' && this.deps.roleId && this.deps.persona && this.deps.devices) {
533
+ try {
534
+ if (await isRoleDirectorSession(this.deps.roleId, sessionId)) {
535
+ const scan = [message.content,
536
+ ...message.msgElements.map((e) => e?.content ?? ''),
537
+ ...message.msgElements.map((e) => e?.url ?? '')].join('\n');
538
+ const link = this.deps.devices.detectLink(scan);
539
+ if (link) {
540
+ const r = await this.deps.devices.activate(this.deps.roleId, link.token, { openid: message.senderId });
541
+ if (r.ok) {
542
+ consumedLinkRaw = link.raw;
543
+ extras.unshift(`[设备] 「${r.alias}」已通过你发来的分享链接激活。操控方式见 memory/设备.md。`);
544
+ } else if (r.code === 'no-device') {
545
+ await this.deps.api.sendText(message.reply, '你还没给这个角色配可用设备:请到管理台「我的设备」登记设备并为角色勾选,然后再发一次分享链接。', message.id).catch(() => {});
546
+ } else if (r.code !== 'not-owner') {
547
+ await this.deps.api.sendText(message.reply, '设备分享链接无效或已过期,请重新生成后再发。', message.id).catch(() => {});
548
+ }
549
+ }
550
+ }
551
+ } catch (e) { this.deps.log.warn('device activate failed: %o', e); }
552
+ }
553
+ const text = assembleText(consumedLinkRaw ? cleaned.replace(consumedLinkRaw, '') : cleaned, quote, extras);
528
554
  if (text.length === 0 && imageBlocks.length === 0) {
529
555
  this.stopTyping(sessionId);
530
556
  return;
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ import { recoverLifeScripts } from './agent-life.js';
21
21
  import { registerRoleProvider, unregisterRoleProvider, syncAllRoleProviders } from './llm-provider.js';
22
22
  import { registerStandingTools } from './tools.js';
23
23
  import { botIdOfSession } from './inbound.js';
24
+ import { createDeviceManager } from './devices/manager.mjs';
24
25
  import * as personaLib from './persona.js';
25
26
 
26
27
  // Re-export the schema so DSH can mount this plugin via `name: 'pygmalion'`.
@@ -79,7 +80,7 @@ async function ensureInstalled(home, persona, log) {
79
80
  log?.warn?.('pygmalion: preset 自动安装失败 %o', e);
80
81
  }
81
82
  try {
82
- for (const d of [persona.accountsDir(), persona.rolesDir()]) await mkdir(d, { recursive: true });
83
+ for (const d of [persona.accountsDir(), persona.rolesDir(), persona.devicesDir()]) await mkdir(d, { recursive: true });
83
84
  log?.info?.('pygmalion: 数据目录已就位 %s', persona.dataRoot());
84
85
  } catch (e) {
85
86
  log?.warn?.('pygmalion: 数据目录初始化失败 %o', e);
@@ -95,6 +96,8 @@ export function apply(ctx, config) {
95
96
  const workspaceRegistry = ctx.workspaceRegistry;
96
97
  const { attachments, approval, agentPresets, webServer, settings, credentials } = resolveOptionalServices(ctx, log);
97
98
  const persona = personaLib;
99
+ // 设备远控 DeviceManager:进程内持有每角色设备运行时(连接/计时/脚本/唤醒)。
100
+ const devices = createDeviceManager({ persona: personaLib, log });
98
101
  // 一行安装自注册:preset 复制 + 数据目录初始化(后台执行,不阻塞插件加载)。
99
102
  void ensureInstalled(home, persona, log);
100
103
  // 自定义 LLM provider:启动时把各角色配置的 apiUrl/apiKey 注册进 dsh(live 生效)。
@@ -170,6 +173,7 @@ export function apply(ctx, config) {
170
173
  agents, sessionPersistence, workspaceRegistry,
171
174
  attachments, approval, agentPresets, webServer,
172
175
  persona, log, storages, config,
176
+ devices,
173
177
  director: ctx, // 供 bot-factory/setup-agent 经 ctx.get('pygmalion.director') 取服务
174
178
  };
175
179
  const manager = createBotManager({
@@ -211,6 +215,7 @@ export function apply(ctx, config) {
211
215
  log,
212
216
  web: config.web,
213
217
  llmProviders,
218
+ devices,
214
219
  botApi: {
215
220
  list: () => manager.getBots(),
216
221
  upsertForRole: (roleId, input) => manager.upsertForRole(roleId, input),
@@ -224,6 +229,7 @@ export function apply(ctx, config) {
224
229
  return () => {
225
230
  try { heartbeat?.stop(); } catch { /* ignore */ }
226
231
  try { manager.stopAll(); } catch { /* ignore */ }
232
+ try { void devices.dispose(); } catch { /* ignore */ }
227
233
  void web?.stop().catch(() => { /* ignore */ });
228
234
  };
229
235
  }, 'pygmalion.gateway()');
@@ -14,7 +14,7 @@ import { join } from 'node:path';
14
14
  import { cleanUserText, isSystemText, readSessionText, parseEvents, extractMessages } from './session-log.js';
15
15
 
16
16
  /** 唤醒/归档/生活情境与 HTTP 推送记录的行首标记(与 wakeup.js / http-api.js 前缀一致)。 */
17
- const INJECTION_LINE = /^\[(唤醒事件|生活窗口|归档任务|HTTP 推送记录)/;
17
+ const INJECTION_LINE = /^\[(唤醒事件|生活窗口|归档任务|设备事件|设备|HTTP 推送记录)/;
18
18
 
19
19
  function pad(n) { return String(n).padStart(2, '0'); }
20
20
  function localDateOf(ms) { const d = new Date(ms); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }