pygmalion 0.1.15 → 0.2.0
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/LICENSE +21 -0
- package/README.md +141 -70
- package/THIRD_PARTY.md +9 -0
- package/docs/ARCHITECTURE.md +66 -108
- package/docs/DEPLOY.md +33 -137
- package/docs/DEVELOPMENT.md +63 -0
- package/docs/DEVICE.md +56 -47
- package/docs/EXTENSIONS.md +176 -0
- package/docs/PRESET.md +21 -63
- package/docs/UPGRADE-0.2.md +52 -0
- package/package.json +52 -33
- package/preset/pygmalion-director/cordis.patch.yml +234 -0
- package/preset/pygmalion-director/pygmalion-tools.js +43 -41
- package/scripts/start-local-test.mjs +45 -45
- package/skills/pygmalion-life-scripts/SKILL.md +12 -0
- package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
- package/skills/pygmalion-memory-archive/SKILL.md +24 -0
- package/skills/pygmalion-toy-control/SKILL.md +16 -0
- package/src/agent-life.js +608 -606
- package/src/archive-tools.js +9 -0
- package/src/bot-factory.js +129 -311
- package/src/bots.js +264 -275
- package/src/channel-qq.js +262 -0
- package/src/config.js +69 -68
- package/src/delivery-receipt.js +36 -0
- package/src/delivery-scope.js +20 -0
- package/src/devices/manager.mjs +80 -570
- package/src/devices/monsterparty-controller.mjs +393 -0
- package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
- package/src/devices/monsterparty.mjs +294 -294
- package/src/devices/pb.mjs +110 -110
- package/src/devices/registry.mjs +19 -0
- package/src/devices/script-helper.mjs +45 -0
- package/src/devices/scripts.mjs +109 -0
- package/src/devices/service.mjs +254 -0
- package/src/director-messages.js +35 -0
- package/src/dsh-runtime.js +17 -0
- package/src/extension-config.js +20 -0
- package/src/extensions.js +118 -0
- package/src/heartbeat.js +118 -97
- package/src/http-api.js +519 -509
- package/src/inbound.js +36 -207
- package/src/index.js +109 -37
- package/src/llm-provider.js +214 -171
- package/src/meme-worker.js +35 -39
- package/src/memebox.js +1 -1
- package/src/memory-recall.js +55 -0
- package/src/memory-write.js +136 -133
- package/src/peer-identity.js +26 -0
- package/src/persona.js +132 -69
- package/src/role-agent.js +155 -0
- package/src/role-runtime.js +65 -0
- package/src/roleplay-config.js +37 -0
- package/src/roleplay-format.js +37 -0
- package/src/roleplay-generation.js +36 -0
- package/src/roleplay-materials.js +113 -0
- package/src/roleplay-output.js +19 -0
- package/src/roleplay-parallel.js +239 -0
- package/src/roleplay-session.js +128 -0
- package/src/roleplay-worker.js +10 -0
- package/src/session-log.js +180 -172
- package/src/setup-agent.js +92 -100
- package/src/skills.js +97 -0
- package/src/slash-commands.js +155 -142
- package/src/speech-input.js +20 -0
- package/src/threads.js +2 -1
- package/src/tools.js +226 -254
- package/src/voice-defaults.js +13 -0
- package/src/voice-mimo.js +139 -125
- package/src/voice.js +200 -0
- package/src/wakeup.js +85 -66
- package/src/web-public/app.js +542 -382
- package/src/web-public/index.html +161 -158
- package/src/web-public/layout.css +7 -7
- package/src/web-public/style.css +12 -8
- package/src/web-server.js +161 -102
- package/src/worker-tools.js +18 -0
- package/templates/sample-life.mjs +59 -59
- package/templates/sample-toy.mjs +33 -33
- package/preset/pygmalion-director/agent.cordis.yml +0 -262
- package/preset/pygmalion-director/preset.yml +0 -3
- package/src/message-review.js +0 -276
|
@@ -1,294 +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
|
-
}
|
|
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
|
+
}
|